|
小弟刚开始学C语言,问题很菜,但google,百度没搜到有用的结果,可能有用的没看到吧
我抄了GNU/Linux编程指南(第二版)上网络编程的第一个例子,最简单的服务器server.c
- #include <stdio.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <netdb.h>
- int port = 8000;
- void main(){
- //struct socketaddr_in sin;
- struct socketaddr_in sin;
- //struct socketaddr_in pin;
- struct socketaddr_in sin;
- int sock_desc;
- int tmp_sock_desc;
- int address_size;
- char buf[16384];
- int i, len;
- //新加入
- address_size = sizeof(pin);
- //创建套接口
- sock_desc = socket(AF_INET,SOCK_STREAM,0);
- if(sock_desc == -1){
- perror("call to socket");
- exit(1);
- }
-
- //初始化套接口
- bzero(&sin,sizeof(sin));
- sin.sin_family = AF_INET;
- sin.sin_addr.s_addr = INADDR_ANY;
- sin.sin_port = htons(port);
-
- //绑定
- if(bind(sock_desc,(struct socketaddr *) &sin,sizeof(sin)) == -1){
- perror("call to bind");
- exit(1);
- }
-
- //开始监听
- if(listen(sock_desc,20) == -1){
- perror("call to listen");
- exit(1);
- }
- printf("Accepting connections ...\n");
-
- while(1){
- //创建临时套接口
- tmp_sock_desc = accept(sock_desc,(struct sockaddr *) &pin,&address_size);
- if(tmp_sock_desc == -1){
- perror("call to accept");
- exit(1);
- }
-
- //接收数据
- if(recv(tmp_sock_desc,buf,16384,0) == -1){
- perror("call to recv");
- exit(1);
- }
- printf("received from client %s\n",buf);
- //处理接收数据
- len = strlen(buf);
- for(i=0;i<=len;i++){
- buf[i] = toupper(buf[i]);
- }
-
- //发送数据
- if(send(tmp_sock_desc,buf,len,0) == -1){
- perror("call to send");
- exit(1);
- }
- close(tmp_sock_desc);
- }
- }
复制代码
make server
出现以下错误:
- etch:~/cs# make server
- cc server.c -o server
- server.c: In function ‘main’:
- server.c:10: error: storage size of ‘sin’ isn’t known
- server.c:11: error: storage size of ‘pin’ isn’t known
- server.c:22: warning: incompatible implicit declaration of built-in function ‘exit’
- server.c:26: warning: incompatible implicit declaration of built-in function ‘bzero’
- server.c:34: warning: incompatible implicit declaration of built-in function ‘exit’
- server.c:40: warning: incompatible implicit declaration of built-in function ‘exit’
- server.c:49: warning: incompatible implicit declaration of built-in function ‘exit’
- server.c:55: warning: incompatible implicit declaration of built-in function ‘exit’
- server.c:60: warning: incompatible implicit declaration of built-in function ‘strlen’
- server.c:68: warning: incompatible implicit declaration of built-in function ‘exit’
- server.c:9: warning: return type of ‘main’ is not ‘int’
- make: *** [server] Error 1
复制代码
问题应该出在sockaddr_in这个结构,它的声明在netinet/in.h
- struct sockaddr_in
- {
- __SOCKADDR_COMMON (sin_);
- in_port_t sin_port; /* Port number. */
- struct in_addr sin_addr; /* Internet address. */
- /* Pad to size of `struct sockaddr'. */
- unsigned char sin_zero[sizeof (struct sockaddr) -
- __SOCKADDR_COMMON_SIZE -
- sizeof (in_port_t) -
- sizeof (struct in_addr)];
- };
复制代码
这个错误是什么意思?是不是我少写了什么东西?
- error: storage size of ‘sin’ isn’t known
复制代码 |
|