简体   繁体   中英

Udp socket binding failed

I am trying to connect a UDP server running on Node.js using

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 . However sendto is working fine without binding to it.

What could be the issue. Also I am not getting 'close' event to on node.js

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. This obviously will lead to bind error that you see. You are trying to tie the client to an IP that belongs to an external system.

And sendto is fine because there is implicit bind on the client side.

Clients need not bind explicitly. You can do away with that part.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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