1.Windows SocketåLinux Socketç¼ç¨çåºå«
Windows SocketåLinux Socketç¼ç¨çåºå«
SOCKETå¨åçä¸åºè¯¥æ¯ä¸æ ·çï¼åªæ¯ä¸åç³»ç»çè¿è¡æºç½®æäºä¸åã
Socket ç¼ç¨ windowså°Linux代ç 移æ¤éå°çé®é¢
1ãä¸äºå¸¸ç¨å½æ°ç移æ¤
2ãç½ç»
socketç¸å ³ç¨åºä»windows移æ¤å°linuxä¸éè¦æ³¨æç
1)头æ件
windowsä¸winsock.h/winsock2.h
linuxä¸sys/socket.h
é误å¤çï¼errno.h
å ¶ä»å¸¸ç¨å½æ°ç头æ件å¯å°å½ä»¤è¡ä¸ç¨manæ令æ¥è¯¢ã
2)åå§å
windowsä¸éè¦ç¨WSAStartup
linuxä¸ä¸éè¦ï¼å¾æ¹ä¾¿ï¼ï¼ç´æ¥å¯ä»¥ä½¿ç¨
3)å ³ésocket
windowsä¸closesocket(...)
linuxä¸close(...)
4)ç±»å
windowsä¸SOCKET
å¨linuxä¸ä¸ºintç±»å
5)ç»å®å°åçç»æä½
å称ç¸åï¼é½æ¯struct sockaddrãstruct sockaddr_inï¼è¿ä¸¤è é常转æ¢ä½¿ç¨ï¼
å¨Windowsä¸é¢å称é½æ¯å¤§åï¼èå¨Linuxä¸ä¸ºå°å
常ç¨ï¼
Linuxä¸ï¼
sockaddr_in destAddr;
destAdd.sin_family=AF_INET;
destAddr.sin_port=htons();
destAddr.sin_addr.s_addr=inet_addr("..1.1");
Windowsä¸ï¼
SOCKADDR_IN destAddr;
destAddr.sin_addr.S_un.S_addr=inet_addr("..1.1");
ä½ç»æä½ä¸æåçå称ä¸å
Windowsä¸ç»æä½æå
struct sockaddr_in {
short sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
struct sockaddr {
u_short sa_family;
char sa_data[];
};
struct in_addr {
union {
struct { u_char s_b1,防洪商业源码s_b2,s_b3,s_b4; } S_un_b;
struct { u_short s_w1,s_w2; } S_un_w;
u_long S_addr;
} S_un;
};
ä¸é¢çä¸äºå®å¯ä»¥ä½¿windowsä¸çç¨åºç§»æ¤å°linuxä¸ï¼éè¿ç±»åçéæ°å®ä¹ï¼ä½¿ä»£ç å ·ælinuxåwindowsä¸ç移æ¤æ§ï¼
[cpp] view plaincopy
#ifdef WIN
typedef int socklen_t;
typedef int ssize_t;
#endif
#ifdef __LINUX__
typedef int SOCKET;
typedef unsigned char BYTE;
typedef unsigned long DWORD;
#define FALSE 0
#define SOCKET_ERROR (-1)
#endif
[cpp] view plaincopy
#ifdef WIN
typedef int socklen_t;
typedef int ssize_t;
#endif
#ifdef __LINUX__
typedef int SOCKET;
typedef unsigned char BYTE;
typedef unsigned long DWORD;
#define FALSE 0
#define SOCKET_ERROR (-1)
#endif
6)è·åé误ç
windowsä¸getlasterror()/WSAGetLastError()
linuxä¸errnoåé
7)设置éé»å¡
windowsä¸ioctlsocket()
linuxä¸fcntl() <fcntl.h>
8)sendå½æ°æåä¸ä¸ªåæ°
windowsä¸ä¸è¬è®¾ç½®ä¸º0
linuxä¸æ好设置为MSG_NOSIGNALï¼å¦æä¸è®¾ç½®ï¼å¨åéåºéåæå¯ è½ä¼å¯¼è´ç¨åºéåºã
9)毫ç§çº§æ¶é´è·å
windowsä¸GetTickCount()
linuxä¸gettimeofday()
)æ°æ®ç±»åçä¸äºè½¬å
éç¨çï¼
å°ç«¯å°å¤§ç«¯ï¼ç½ç»å议使ç¨ï¼ç转æ¢ï¼htonl, htons
ç¹ååè¿å¶IPåæ´æ°ä¹é´çç¸äºè½¬æ¢ï¼inet_addr()ï¼è¯¥å½æ°å°ç¹ååè¿å¶è½¬ä¸ºæ´æ°ï¼ï¼inet_aton()ï¼inet_ntoa()ï¼inet_pton()ï¼linuxä¸ç¬æ 该å½æ°å¯ä»¥å®ç°ç¸äºä¹é´ç转æ¢ï¼
使ç¨å°ç头æ件ä¸ç¸åï¼linuxä¸ç¨manå½ä»¤æ¥è¯¢ã
å¦å¤æ³¨æï¼
linuxä¸ä½¿ç¨çå¥æ¥å为伯å å©å¥æ¥åï¼å æ¤å¨select()å½æ°ç使ç¨ä¸ï¼ç¬¬ä¸ä¸ªåæ°ç设置ï¼ä¹æåºå«ï¼
windowsä¸ä¸ºäºä¸ä¼¯å å©å¥æ¥åå¹é ï¼ç¬¬ä¸ä¸ªåæ°æ¯æ æè°ï¼ä¸è¬å¯è®¾ä¸º0ï¼
int maxfdpæ¯ä¸ä¸ªæ´æ°å¼ï¼æ¯æéåä¸æææ件æ述符çèå´ï¼å³æææ件æ述符çæ大å¼å 1ï¼ä¸è½éï¼
3ãå¤çº¿ç¨
å¤çº¿ç¨: (win)process.h --ã(linux)pthread.h
_beginthread --> pthread_create
_endthread --> pthread_exit