Socket Programming in C: The first accept() always gives me address filled with 0s
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(){
struct sockaddr_in svraddr;
int clisock;
pid_t pid;
ssize_t nlen;
struct sockaddr_in cliaddr;
socklen_t cliaddrlen = sizeof(sockaddr_in);
char buf[BUFSIZ];
svraddr.sin_family=AF_INET;
svra开发者_开发知识库ddr.sin_port=htons(49510);
svraddr.sin_addr.s_addr=htonl(INADDR_ANY);
int serversock = socket(PF_INET,SOCK_STREAM,0);
if(serversock==-1){
perror("socket()");
exit(1);
}
if(bind(serversock,(struct sockaddr*)&svraddr,sizeof(svraddr))==-1){
perror("bind()");exit(1);
}
if(listen(serversock,10)==-1){
perror("listen()");exit(1);
}
while(1){
clisock = accept(serversock,(struct sockaddr*)&cliaddr,&cliaddrlen);
switch(pid=fork()){
case -1:
perror("fork()");exit(1);
case 0:
close(serversock);
printf("CONN: client %s:%d\n",inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.sin_port));
while((nlen=read(clisock,buf,BUFSIZ))!=0){
perror("read");
printf("RECV: srcport %d, %s\n",ntohs(cliaddr.sin_port),buf);
write(clisock,"received successfully",22);
}
close(clisock);
printf("DISCONN: client %d disconnected\n",ntohs(cliaddr.sin_port));
exit(0);
break;
default:
close(clisock);
}
}
}
Above is the entire codes for server. It is simple multiprocess based server.
what I understood is : accept() should give client address into cliaddr. it does, but it doesn't for the first one.
but strangely, Socket I/O works well.
the code is written from scratch. What did I do wrong with this?
I tried initializing cliaddr with memset, no luck.
output for server is:
CONN: client 0.0.0.0:0
DISCONN: client 0 disconnected
CONN: client 127.0.0.1:57078
DISCONN: client 57078 disconnected
accept() should always gives correct client address anytime.
Never mind. I've figure out why.
socklen_t cliaddrlen = sizeof(sockaddr_in);
=>
socklen_t cliaddrlen = sizeof(struct sockaddr_in);
I don't understand why this code's been successfully compiled. but yes, my mistake. now it works like charm.
精彩评论