本来不想写这篇文章的,发现网上真很难找到windows下socket的编程的示例代码。而自己又不能一下仔背过这么多的规范,虽然代码不少也贴上来吧,代码解析就先免一点了,有代码而在网上找解析还是挺简单的,以后也好找点~~
可能其他方式也能实现,我会一种也差不多了,呵呵。
有点需要特别注意的,因为我用的是MinGW为C编译器,所以编译的时候需要加上-lwsock32的参数。
如: gcc server.c -o server -lwsock32
服务器端代码:
#include<stdio.h>
#include<winsock.h>
#pragma comment (lib, "ws2_32.lib")
BOOL InitWinsock();
void main(){
SOCKET socket1;
InitWinsock();
struct sockaddr_in local;
local.sin_family=AF_INET;
local.sin_port=htons(3490); ///监听端口
local.sin_addr.s_addr=INADDR_ANY; ///本机
memset(local.sin_zero,0,8);
socket1=socket(AF_INET,SOCK_STREAM,0);
int bind_result = bind(socket1,(struct sockaddr*)&local,sizeof(local));
while (1){
int nlisten = listen(socket1, 10);
printf("Listening......\n");
struct sockaddr_in their_addr;
int nSize = sizeof(their_addr);
int nNewFd = accept(socket1, (struct sockaddr*)&their_addr, &nSize);
printf("Accepted! IP:%s: Port:%d\n", inet_ntoa(their_addr.sin_addr), ntohs(their_addr.sin_port));
Sleep(500);
}
closesocket(socket1);
}
BOOL InitWinsock(){
int Error;
WORD VersionRequested;
WSADATA WsaData;
VersionRequested=MAKEWORD(2,2);
Error=WSAStartup(VersionRequested,&WsaData); //启动WinSock2
if(Error!=0){
return FALSE;
}
else {
if(LOBYTE(WsaData.wVersion)!=2||HIBYTE(WsaData.wHighVersion)!=2){
WSACleanup();
return FALSE;
}
}
return TRUE;
}
客户段代码:
#include<stdio.h>
#include<winsock.h>
#pragma comment (lib, "ws2_32.lib")
BOOL InitWinsock();
void main(){
SOCKET socket1;
InitWinsock();
struct sockaddr_in from;
struct sockaddr_in local;
local.sin_family = AF_INET;
local.sin_port = htons(888);
local.sin_addr.s_addr = INADDR_ANY;
int fromlen =sizeof (from);
socket1 = socket(AF_INET,SOCK_STREAM,0);
int nbind = bind(socket1,(struct sockaddr*)&local, sizeof(local));
if (nbind < 0){
printf("error");
exit(1);
}
from.sin_family = AF_INET;
from.sin_port = htons(3490);
from.sin_addr.S_un.S_addr = inet_addr("10.10.110.249");
memset(from.sin_zero, 0, 8);
int nCon = connect(socket1, (struct sockaddr*)& from, sizeof (from));
if (nCon < 0){
printf("error");
exit(1);
}
}
BOOL InitWinsock(){
int Error;
WORD VersionRequested;
WSADATA WsaData;
VersionRequested = MAKEWORD(2,2);
Error = WSAStartup(VersionRequested, &WsaData);
if (Error != 0){
return FALSE;
}
else {
if(LOBYTE(WsaData.wVersion) != 2 || HIBYTE(WsaData.wHighVersion) != 2){
WSACleanup();
return FALSE;
}
}
return TRUE;
}