Reputation: 575
My website can be accessed using any of 2 different static IPs (IPv4).
Is it possible to open a TCP connection to another server, specifying which of the 2 IPs to use as a return address ?
x.x.x.x (my server) => z.z.z.z (destination server)
y.y.y.y (my server) => z.z.z.z (destination server)
Error-checking, etc. in this example has been omitted for simplicity sakes :
struct addrinfo hints, *result;
hints.ai_flags = 0;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_addrlen = 0;
hints.ai_canonname = NULL;
hints.ai_addr = NULL;
hints.ai_next = NULL;
getaddrinfo(domain, "80", &hints, &result);
socket(result->ai_family, result->ai_socktype, result->ai_protocol);
Upvotes: 2
Views: 7796
Reputation: 409136
Like @hochl says, you use the bind
system call:
struct sockaddr_in sin = { 0 };
int sock;
/* Create a socket address, with a specific port and (local) ipnumber */
sin.sin_family = AF_INET;
sin.sin_port = htons(80);
inet_aton("1.2.3.4", &sin.sin_addr);
/* Create socket */
sock = socket(AF_INET, SOCK_STREAM, 0);
/* Bind socket to the local address */
bind(sock, (struct sockaddr *) &sin, sizeof(sin));
/* Now connect to remote server... */
/* connect(...) */
It should be noted that use of inet_aton
is normally discouraged, in favor of inet_pton
.
Upvotes: 6
Reputation: 12920
Not sure, but can't you bind
your socket to one of your local addresses before you connect? In this case you may choose which of your IPs is used for the connection.
Upvotes: 1