开发者

C Programming Using a specific Host IP to connect to server

开发者 https://www.devze.com 2023-04-05 11:06 出处:网络
I am looking at a machine with multiple IP address (ex ethernet and wireles开发者_开发技巧s) and need my client to connect to a server using a specific Client IP address.I can perform this easy in Jav

I am looking at a machine with multiple IP address (ex ethernet and wireles开发者_开发技巧s) and need my client to connect to a server using a specific Client IP address. I can perform this easy in Java (done doing the Socket() with 4 args), but the only reference to use a specific host IP address that I can see is with using bind() but as far as I know that only is used for servers.

Synopsis: Client has 2 IP address (ethernet and wireless) trying to connect to a server.. but using a specific IP (don't need to worry about "finding" the IP addresses as they will be in a config file or DEFINE

Not a windows only answer but a C programing that is portable (I use mac osx/linux usually but also windows)


I've never done this before but I think you can bind a socket to an ip address and then use connect with that socket. The pertinent section from here http://pubs.opengroup.org/onlinepubs/009695399/functions/connect.html states:

If the socket has not already been bound to a local address, connect() shall bind it to an address which, unless the socket's address family is AF_UNIX, is an unused local address.

Which implies that bind can be used before connect.


Your reference is correct. If you use bind(), then that address will be used to bind the client socket to the interface you want to use. bind() is not only used for server sockets.


https://beej.us/guide/bgnet/html/multi/syscalls.html#bind

By using the AI_PASSIVE flag, I'm telling the program to bind to the IP of the host it's running on. If you want to bind to a specific local IP address, drop the AI_PASSIVE and put an IP address in for the first argument to getaddrinfo().

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号