注: 如果使用MinGW编译,加上选项-lwsock32,否则因为MinGW与VC库调用函数约定不同,其函数符号也不同,无法找到windows SDK
中的ws2_32.lib中相应的函数符号。使用此选项则调用MinGW提供的winsock库。-m32指示将目标文件编译成32位程序。
client 客户端:
#undef UNICODE
/*
author : ez
date : 2015/7/11
describe : a tcp socket server
this code only run on windows platform
note : if you use MinGW to compile, please enter:
mingw32-gcc -o client client.c -m32 -lwsock32
-m32 option specified your target PE form is 32bits
*/
#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x501
#include <winsock2.h>
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#pragma comment (lib, "ws2_32.lib")
# define DEFAULT_BUFLEN 0x100
# define DEFAULT_PORT 9003
# define DEFAULT_ADDR "127.0.0.1"
typedef char byte;
byte recvbuf [DEFAULT_BUFLEN];
int main (int argc, char* argv []) {
WSADATA wsaData;
int res;
SOCKET srv_socket = INVALID_SOCKET;
SOCKET client_socket = INVALID_SOCKET;
// defined in <winsock2.h>
// struct sockaddr *result = NULL;
struct sockaddr_in hints;
int sent_len = 0;
int recv_len = DEFAULT_BUFLEN;
// Initialize Winsock
res = WSAStartup (MAKEWORD (2,2), &wsaData);
if