我遇見的問題及解決方案
昨晚寫了個socket程式,最簡單的服務端和用戶端
由於我的用戶端是個一次性的程式,串連一次服務端就會自動推出,然後重新運行./client後才能再次串連服務端
我發現第一次用戶端串連服務端的時候,服務端列印的用戶端地址是一個非127.0.0.1,是不對的!連接埠號碼為1023,如:
開始我以為是我的服務端中的使用者accept函數的sockaddr_in 結構體沒有初始化造成的,後來我加入了bzero(&cin,sizeof(cin));語句用於cin結構體的初始化
然後我發現第一次串連變成了0.0.0.0,連接埠也為0!為什嗎?
百度了一下才發現一個人的socket程式中在調用accept函數前,先給accept函數需要的參數len賦值
len = sizeof(cliaddr);
然後再調用accept
fc = accept(listenfd, (struct sockaddr *) &cin, &len);
測試後果然不錯了!這樣就知道我的錯誤在於accept函數的參數錯誤!
accept函數
查了我當前系統(Linux 2.6.35.14-106.fc14.i686)的標頭檔,在/Usr/include/Sys/socket.h中這樣定義了accept函數
/* Await a connection on socket FD. When a connection arrives,open a new socket to communicate with it, set *ADDR (which is*ADDR_LEN bytes long) to the address of the connecting peer and *ADDR_LEN to theaddress's actual length, and return the new socket's descriptor, or-1 for errors. This function is acancellation point and therefore not marked with __THROW. */extern int accept (int __fd, __SOCKADDR_ARG __addr, socklen_t*__restrict __addr_len);
在網上發現有人說accept函數的最後一個參數可以為NULL,我便也測試了下,代碼如下
fc = accept(fs,(struct sockaddr*)&cin , NULL); if(fc < 0) { printf("fc==%d\n",fc); return -1; }
運行時發現運行到這兒退出了,列印了fc==-1!由此可見,最後一個參數不為NULL最好!(可能是系統版本不同導致的)
我的server.c
#include<stdio.h>#include<stdlib.h>#include<string.h>#include<arpa/inet.h>#define MAX_LINE 100#define PORT 8000void my_fun(char *p);/*大寫字元轉換為小寫字母*/void my_fun(char *p){ if(p == NULL) return ; for ( ;*p != '\0';p++ ) { if(*p >= 'A' && *p <= 'Z') { *p = *p - 'A' + 'a'; } }}int main(int argc , char **argv){ struct sockaddr_in sin; struct sockaddr_in cin; int fs, fc; //建立通訊端用,服務端和用戶端各一個 socklen_t len; char buf[MAX_LINE]; char addr_p[INET_ADDRSTRLEN];//用來儲存用戶端ip資訊 int n; bzero(&sin,sizeof(sin)); bzero(&cin,sizeof(cin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = INADDR_ANY; //服務端接受任意地址 sin.sin_port = htons(PORT); fs = socket(AF_INET,SOCK_STREAM,0); //服務端通訊端,tcp協議 bind(fs,(struct sockaddr*)&sin,sizeof(sin)); listen(fs,10); printf("=========welcome to jack's server=========\n"); memset(addr_p,0,sizeof(addr_p)); while (1) { len = sizeof(cin);//len 必須賦值,否則得到的第一個用戶端地址為0.0.0.0! printf("len == %d\n",len); fc = accept(fs,(struct sockaddr*)&cin , &len); //fc = accept(fs,(struct sockaddr*)&cin , NULL);//盡量不要為NULL if(fc < 0) { printf("fc==%d\n",fc); return -1; } n = read(fc,buf,MAX_LINE); //讀取的長度為n inet_ntop(AF_INET,&cin.sin_addr,addr_p,sizeof(addr_p)); printf("client ip:%s,port:%d\n",addr_p,ntohs(cin.sin_port)); printf("content:%s\n",buf); my_fun(buf); write(fc,buf,n); close(fc); } if(close(fs) == -1) { perror("fail to close\n"); exit(1); } return 1;}
好好學習,天天向上!!