我开始在Windows上用C语言编写套接字,只是为了学习如何在客户端和服务器应用程序中使用套接字,这是一个简单的例子。
这是我的服务器代码
#if defined WIN32
#include <winsock2.h>
#include <winsock.h>
#else
#define closesocket closeter
#include <sys/socket.h>
#include <arp /a inet.h>
#include <unistd.h>
#endif
#include <stdio.h>
#include <stdlib.h> // for atoi()
#define PROTOPORT 8080 // default protocol port number
#define QLEN 6 // size of request queue
void ErrorHandler(char *errorMessage) {
printf(errorMessage);
}
void ClearWinSock() {
#if defined WIN32
WSACleanup();
#endif
}
int main(int argc, char *argv[]) {
int port;
if (argc > 1) {
port = atoi(argv[1]);
} else
port = PROTOPORT; // use default port number
if (port < 0) {
printf("bad port number %s \n", argv[1]);
return 0;
}
#if defined WIN32 // initialize Winsock
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
ErrorHandler("Error at WSAStartup()\n");
return 0;
}
#endif
int MySocket;
MySocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (MySocket < 0) {
ErrorHandler("socket creation failed.\n");
ClearWinSock();
return 0;
}
struct sockaddr_in sad;
memset(&sad, 0, sizeof(sad)); // ensures that extra bytes contain 0
sad.sin_family = AF_INET;
sad.sin_addr.s_addr = inet_addr("127.0.0.1");
sad.sin_port = htons(port);
if (bind(MySocket, (struct sockaddr*) &sad, sizeof(sad)) < 0) {
printf("Bind failed with error code : %d" , WSAGetLastError());
closesocket(MySocket);
ClearWinSock();
return 0;
}
if (listen (MySocket, QLEN) < 0) {
ErrorHandler("listen() failed.\n");
closesocket(MySocket);
ClearWinSock();
return 0;
}
struct sockaddr_in cad; // structure for the client address
int clientSocket; // socket descriptor for the client
int clientLen; // the size of the client address
printf("Waiting for a client to connect...");
while (1) {
clientLen = sizeof(cad); // set the size of the client address
if ((clientSocket = accept(MySocket, (struct sockaddr *)&cad,
&clientLen)) < 0) {
ErrorHandler("accept() filed.\n");
closesocket(MySocket);
ClearWinSock();
return 0;
}
printf("Handling client %s\n", inet_ntoa(cad.sin_addr));
}
}// end of main
当我运行它时,控制台会显示以下消息: 绑定失败,错误代码:10048 这意味着函数bind返回非零值,因此发生错误,10048错误。我知道这个错误意味着spicified端口已被其他应用程序使用,所以我试图多次更改端口号,但它仍然显示我相同的错误。 谢谢你的帮助!