C语言,socket为什么运行不了,我这个是关于udp通信的接收方代码
发布网友
发布时间:2024-05-02 12:14
我来回答
共2个回答
热心网友
时间:2024-11-20 04:43
s = socket(AF_INET, SOCK_DGRAM, 0); // 1
if (WSAStartup(MAKEWORD(2,2), &wsd) != 0) // 2
{
printf("Failed to load Winsock!\n");
return 1;
}
1、2反了,要先初始化才能socket。既然你用vs,推荐你看一下《Windows网络编程技术》和配套代码,可以省去很多麻烦。
热心网友
时间:2024-11-20 04:43
#include "stdafx.h"
#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>
#pragma comment( lib, "ws2_32.lib" ) // 1
#define PORT 12345
int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wsd; //2
if (WSAStartup(MAKEWORD(2,2), &wsd) != 0)
{
printf("Failed to load Winsock!\n");
return 1;
}
SOCKET s; //2
int ret;
struct sockaddr_in local,sender;
s = socket(AF_INET, SOCK_DGRAM, 0);
if(s == INVALID_SOCKET)
return 1;
local.sin_family = AF_INET;
local.sin_port = htons(PORT);
local.sin_addr.s_addr = htonl(INADDR_ANY);
;
int a = 0;
if ((a = bind(s, (struct sockaddr *)&local,sizeof(sockaddr_in))) == SOCKET_ERROR)
{
printf("bind() failed: %d\n", WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
char recvbuf[1024];
int dwSenderSize = sizeof(sockaddr_in); //3
ret = recvfrom(s, recvbuf, 1024, 0, (SOCKADDR *)&sender, &dwSenderSize);
if (ret == SOCKET_ERROR)
{
printf("recvfrom() failed; %d\n", WSAGetLastError());
closesocket(s);
WSACleanup();
}
else if (ret == 0)
{
closesocket(s);
WSACleanup();
}
else
{
recvbuf[ret] = '\0';
printf("%s:%d sent me: '%s'\n", inet_ntoa(sender.sin_addr),ntohs(sender.sin_port), recvbuf);
}
closesocket(s);
WSACleanup();
return 0;
}