简体   繁体   English

Udp套接字绑定失败

[英]Udp socket binding failed

I am trying to connect a UDP server running on Node.js using 我正在尝试连接在Node.js上运行的UDP服务器

int socketDs = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);

struct sockaddr_in socket;
memset(&socket, 0, sizeof(socket));
socket.sin_family = AF_INET;
socket.sin_addr.s_addr = inet_addr("SERVER.IP");
socket.sin_port = htons(PORT);

long r = bind(socketDs, (struct sockaddr *)&socket, sizeof(socket));
NSLog(@"Sockect bind: %ld   %s", r, strerror(errno));

Couldn't bind to it, returns with Can't assign requested address . 无法绑定到它,返回与Can't assign requested address However sendto is working fine without binding to it. 然而,sendto工作正常,没有绑定它。

What could be the issue. 可能是什么问题。 Also I am not getting 'close' event to on node.js 另外,我没有在node.js上收到'close'事件

Here is my server code 这是我的服务器代码

var dgram = require("dgram");
var server = dgram.createSocket("udp4");

var clients = new Array();

server.on("listening", function () {
    var address = server.address();
    console.log("UDP Server listening on " + address.address + ":" + address.port);
});

server.on("message", function (message, remote) {
    console.log(remote.address + ':' + remote.port +' - ' + message);
    }
});

server.on("close") {
    console.log("close");
});

server.on("error") {
    console.log("error");
});

server.bind(PORT);

The first piece of code, you mentioned is that of client. 您提到的第一段代码是客户端代码。 And you are trying to bind to SERVER_IP. 而你正试图绑定到SERVER_IP。 This obviously will lead to bind error that you see. 这显然会导致您看到的bind错误。 You are trying to tie the client to an IP that belongs to an external system. 您正尝试将客户端绑定到属于外部系统的IP。

And sendto is fine because there is implicit bind on the client side. sendto很好,因为客户端有隐式绑定。

Clients need not bind explicitly. 客户端无需显式bind You can do away with that part. 你可以取消那部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM