|
小弟刚开始学习socket编程
照书抄了一段程序,可是在编译的时候却提示出错
[board@board board]$ gcc -o test socket/test1.c
socket/test1.c: In function `main':
socket/test1.c:18: parse error before '{' token
socket/test1.c: At top level:
socket/test1.c:23: parse error before '.' token
socket/test1.c:26: parse error before '&' token
socket/test1.c:31: parse error before numeric constant
socket/test1.c:31: conflicting types for `exit'
/usr/include/stdlib.h:610: previous declaration of `exit'
socket/test1.c:31: warning: data definition has no type or storage class
socket/test1.c:36: parse error before numeric constant
socket/test1.c:36: warning: data definition has no type or storage class
socket/test1.c:46: parse error before string constant
socket/test1.c:51: warning: parameter names (without types) in function declaration
socket/test1.c:51: warning: data definition has no type or storage class
socket/test1.c:52: parse error before numeric constant
socket/test1.c:52: warning: data definition has no type or storage class
socket/test1.c:54: warning: parameter names (without types) in function declaration
socket/test1.c:54: warning: data definition has no type or storage class
socket/test1.c:55: parse error before "while"
程序代码如下:
[code:1]#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#define MYPORT 3388 /*定义用户连接端口*/
#define BACKLOG 10 /*多少等待连接控制*/
main ()
{
int sockfd,new_fd; /*用sockefd进行监听,new_fd建立新的连接*/
struct sockaddr_in my_addr; /*我的地址信息*/
struct sockaddr_in their_addr; /*连接用户的地址信息*/
int sin_size;
if ((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1{
perror("socket");
exit(1);
}
my_addr.sin_family=AF_INET;/*本机字节顺序*/
my_addr.sin_port=htons(MYPORT);/*将本机端口信息转换成网络顺序*/
my_addr.sin_addr.s_addr=INADDR_ANY; /*自动实用本机的ip地址*/
bzero(&(my_addr.sin_zero)),;/*将其他的结构置为空*/
if (bind(sockfd,(struct sockaddr *)&my_addr,sizeof(struct
sockaddr))==-1) {
perror(bind);
exit(1);
}
if (listen(sockfd,BACKLOG)==-1){
perror("listen");
exit(1);
}
while(1){/*主函数accept()循环*/
sin_size=sizeof(struct sockaddr_in);
if ((new_fd=accept(sockfd,(struct sockaddr *)&their_addr,\
&sin)size))==-1{
perror("accept");
continue;
}
printf("server:got connection from %s\n",\
inet_ntoa(their_addr.sin_addr));
if(!fork()){/*这是一个子进程*/
if(send(new_fd,"hello,world!\n",14,0)==-1)
perror("send");
close(new_fd);
exit(0);
}
close(new_fd); /*父进程关闭新的连接*/
while(waitpid(-1,NULL,WNOHANG) > 0); /*清除子进程*/
}
}[/code:1] |
|