linux - How to connect to mail server in C -
i tried make connection mail server in local area network. ip of mail server 192.168.1.1. so, tried following program 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 convert ip 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 connect server\n"); perror(""); exit(1); } else{ printf("successfully connected server...\n"); } }
output:
$ ./a.out unable connect server connection refused $
but via telnet, connected shown below.
$ telnet 192.168.1.1 25 trying 192.168.1.1... connected 192.168.1.1. escape character '^]'. 220 mail.msys.co.in esmtp postfix (debian/gnu) ^] telnet> connection closed. $
so, mistake done here. there wrong in program. request me solve problem , why occurs.
disregarding other problems, causes direct breakage in question (almost certainly, barring "unexpected" host architecture):
sa.sin_port=25;
what need this:
sa.sin_port = htons(25);
ie, have wrong byte order port number, meaning interpreted other number entirely.
from htons(3):
the htons() function converts unsigned short integer hostshort host byte order network byte order.
[snip]
on i386 host byte order least significant byte first, whereas network byte order, used on internet, sig‐ nificant byte first.
if developing on architecture host byte order matched network byte order (ie, both msb), you'd want conversion allow portability.
Comments
Post a Comment