C语言连接邮件服务器的方法

How to connect to mail server in C

我试图连接到局域网中的邮件服务器。邮件服务器的ip是192.168.1.1。所以,我尝试了 下面的程序来测试。

节目:

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
int main()
{
    struct sockaddr_in sa;
    struct in_addr ip;

    int fd=socket(AF_INET,SOCK_STREAM,0);

    if(inet_pton(AF_INET,"192.168.1.1",&ip)==-1){
        printf("Unable to convert ip to binary\n");
        perror("");
        exit(1);
    }

    sa.sin_family=AF_INET;
    sa.sin_port=25;
    sa.sin_addr=ip;

    if(connect(fd,(struct sockaddr*)&sa,sizeof(sa))==-1){
        printf("Unable to connect to server\n");
        perror("");
        exit(1);
    }
    else{
        printf("Successfully connected to server...\n");
    }
}

输出:

$ ./a.out 
Unable to connect to server
Connection refused
$

但是通过telnet,连接成功如下图。

$ telnet 192.168.1.1 25
Trying 192.168.1.1...
Connected to 192.168.1.1.
Escape character is '^]'.
220 mail.msys.co.in ESMTP Postfix (Debian/GNU)
^]
telnet> Connection closed.
$

所以,我在这里犯了什么错误。我的程序有什么问题吗?我请求你帮我解决这个问题以及它为什么会出现。

忽略任何其他问题,导致问题直接中断的原因是(几乎可以肯定,除非 "unexpected" 主机架构):

sa.sin_port=25;

你需要的是这样的:

sa.sin_port = htons(25);

也就是说,您的端口号字节顺序错误,这意味着它将完全被解释为其他数字。

来自 htons(3):

The htons() function converts the unsigned short integer hostshort from host byte order to network byte order.

[snip]

On the i386 the host byte order is Least Significant Byte first, whereas the network byte order, as used on the Internet, is Most Sig‐ nificant Byte first.


即使您在主机字节顺序与网络字节顺序(即两个 MSB)相匹配的体系结构上进行开发,您也希望进行转换以实现可移植性。