C中接收UDP数据包
我一直在尝试使用winsock2包在ms Visual Studio 2008中执行此操作,但是每当我尝试解析有效的输入IP地址时,我都会收到“无效的IP...”错误。我唯一的猜测是存在一些权限错误,但我真的不知道出了什么问题。请帮忙!
if(WSAStartup(MAKEWORD(2,2), &wsaData) != 0){
error("WSAStartup() failed\n\r");
}
// validate port
if( port <= 0 || port > 65535){
sprintf(msg, "Invalid port - %d. Ports must be between 0 and 65536\n\r",
port);
error(msg);
}
// validate ip
inet_addr = inet_addr(ip);
if( inet_addr == INADDR_NONE){
sprintf(msg, "Not an ip - %s\n\r", ip);
error(msg);
} else {
info = gethostbyaddr((char*)&inet_addr, 4, PF_INET);
if(info == NULL){
sprintf(msg, "Invalid ip - %s\n\r", ip);
error(msg);
}
}
I have been trying to do this in ms visual studio 2008 using the winsock2 package but whenever i try to resolve the input ip address, which is valid, I get an "Invalid ip..." error. My only guess is that there is some permissions error, but I really have no clue whats wrong. Please help!
if(WSAStartup(MAKEWORD(2,2), &wsaData) != 0){
error("WSAStartup() failed\n\r");
}
// validate port
if( port <= 0 || port > 65535){
sprintf(msg, "Invalid port - %d. Ports must be between 0 and 65536\n\r",
port);
error(msg);
}
// validate ip
inet_addr = inet_addr(ip);
if( inet_addr == INADDR_NONE){
sprintf(msg, "Not an ip - %s\n\r", ip);
error(msg);
} else {
info = gethostbyaddr((char*)&inet_addr, 4, PF_INET);
if(info == NULL){
sprintf(msg, "Invalid ip - %s\n\r", ip);
error(msg);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要链接
ws2_32.lib
:或者将其作为附加链接器输入放入您的项目配置中。
You need to link with
ws2_32.lib
:Or put it in your project configuration as an additional linker input.
检查您是否链接到 ws2_32.lib。我相信这就是你所需要的。
Check if you are linking to ws2_32.lib. I believe that's what you need.
除非有令人信服的理由保持 Winsock 2.0 兼容性级别(在非常旧的 Windows 版本上运行;使用依赖于较旧 Winsock 行为的其他代码等),否则您可能还需要考虑更改:
if(WSAStartup(MAKEWORD) (2,0), &wsaData) != 0){
到
if(WSAStartup(MAKEWORD(2,2), &wsaData) != 0){
2.2 是 Winsock API 的最新版本。
Unless there's a compelling reason to stay at a Winsock 2.0 compatibility level (running on a very old version of Windows; using other code that relies on older Winsock behavior, etc.), you might also want to consider changing:
if(WSAStartup(MAKEWORD(2,0), &wsaData) != 0){
to
if(WSAStartup(MAKEWORD(2,2), &wsaData) != 0){
2.2 is the latest version of the Winsock API.
端口号 sin_port 也需要采用网络字节顺序,否则您将把套接字绑定到与您想象的完全不同的端口。使用 htons() 并查看其他示例。
(这只适用于小端系统,但无论如何都是个好主意。大多数 Windows 系统都是小端系统。)
The port number sin_port needs to be in network byte order, too, otherwise you'll be binding your socket to a totally different port from what you think. Use htons() and see other examples.
(This only applies on little-endian systems but is a good idea anyway. Most Windows systems are little-endian.)