socket编程在windows和linux下的区别

1.Linux头文件主要包含
  #include <sys/socket.h>
  #include <netinet/in.h>
  #include <netdb.h>
  #include <arpa/inet.h>
  
  而windows下则是包含
  #include <Winsock2.h>
  #pragma comment(lib,“Ws2_32.lib”)

2.初始化
windows下需要用WSAStartup();linux下不需要
对应的退出清理用WSACleanup( );linux下不需要

3.关闭socket
windows下closesocket(…)
linux下close(…)

4.socket套接字类型
Linux中socket为整形,
 Windows中为一个SOCKET类型。
 因为linux中的socket与普通的fd一样,所以可以在TCP的socket中,发送与接收数据时,直接使用read和write。而windows只能使用recv和send。

5.获取错误码
windows下WSAGetLastError() ;
linux下设置errno变量 用geterror()取得错误码;

6.设置socket属性
Linux下为 fcntl (fd, F_SETFL, flag | O_NONBLOCK);
Windows下为 ioctlsocket (fd, FIONBIO, (unsigned long *) &flag);

7.毫秒级时间获取
windows下 GetTickCount()
linux下 gettimeofday()

8.WSA宏
windows下WSA相关的操作
linux下WSA相关的操作在Linux不必要,直接去掉即可

9.多线程
多线程: (win)process.h --〉(linux)pthread.h
_beginthread --> pthread_create
_endthread --> pthread_exit

猜你喜欢

转载自blog.csdn.net/Fengfgg/article/details/112229986