How to connect to mail server in C

2019-09-12 10:16发布

问题:

I tried to make a connection to my mail server which is in local area network. The ip of mail server is 192.168.1.1. So, I tried the following program to test that.

Program:

#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");
    }
}

Output:

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

But via telnet, it is successfully connected as shown below.

$ 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.
$

So, what is the mistake I done here. Is there anything wrong in my program. I request you to help me solve this problem and why it occurs.

回答1:

With a wireshark trace you can see that your code tries to connect to port 6400. Try:

sa.sin_port=htons(25);