Hi all,
I wrote a simple daytime server program,the code is below and i felt
puzzle about the output.(I'll give the output under the code)
#include "unp.h"
#include <time.h>
int main(int argc,char **argv){
struct sockaddr_in servaddr,cliaddr;
socklen_t len;
char buf[BUFSIZ];
int listenfd,connfd;
time_t t;
if((listenfd = socket(AF_INET,SOCK_STREAM,0)) <0 ){
perror("socket");
return -1;
}
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(atoi(argv[1]));
if(bind(listenfd,(SA *)&servaddr,sizeof(servaddr)) < 0){
perror("bind");
return -1;
}
if(listen(listenfd,LISTENQ) < 0){
perror("listen");
return -1;
}
for(;;){
if((connfd = accept(listenfd,(SA *)&cliaddr,&len)) < 0){
if(errno == EINTR) continue;
else return -1;
}
printf("%s\n",cliaddr.sin_family == AF_INET?"AF_INET":"NOT AF_INET");
fprintf(stderr,"connect from %s\nport on %d\n",\
inet_ntop(cliaddr.sin_family,&cliaddr.sin_addr,buf,sizeof(buf)),\
ntohs(cliaddr.sin_port));
t = time(NULL);
sprintf(buf,"%s",ctime(&t));
write(connfd,buf,strlen(buf));
close(connfd);
}
I issued twice connects from the client with ./cli 127.0.0.1 9999 andQuote:}
the output in the server is
$./ser 9999
NOT AF_INET
connect from (null)
port on 1032
AF_INET
connect from 127.0.0.1
port on 55578
I don't understand why there is a (null) IP address here,so i changed
the "inet_ntop" to
inet_ntop(AF_INET,&cliaddr.sin_addr,buf,sizeof(buf)),\
ntohs(cliaddr.sin_port));
the output became:
NOT AF_INET
connect from 128.155.150.0
port on 1032
AF_INET
connect from 127.0.0.1
port on 35763
I don't know where i get the address 128.155.150.0 and i'm sure i set
the AF_INET constant to the client's socket address structure.
Will anyone explain that?
Thanks ahead
Ryan