Reputation: 3549
int server_sockfd, client_sockfd; //server and client filedescriptors
socklen_t server_len, client_len;
struct sockaddr_in server_address; //server address
struct sockaddr_in client_address; //client address
int server_port = 10000;
char *def_server_address ="127.0.0.1";
server_len = sizeof(server_address);
memset(&server_address, 0, server_len );
server_address.sin_family = AF_INET;
if (x == 1) {
server_address.sin_addr.s_addr = INADDR_ANY;}
else {
server_address.sin_addr.s_addr = inet_addr(def_server_address);
}
server_address.sin_port = htons(server_port);
How should I print the address of the server from server_address? Using printf.
Upvotes: 7
Views: 21743
Reputation:
That worked for me:
struct sockaddr_in sa;
char buffer[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &sa.sin_addr, buffer, sizeof(buffer));
printf("address: '%s'\n", buffer);
AF_INET is used to denote that the sin_addr points to an IPv4 network address. The resulting string is copied to the buffer variable. You should specify the number of bytes available in the buffer in the last argument of inet_ntop().
Upvotes: 11
Reputation: 284
I used an example from Beej's Networking: https://beej.us/guide/bgnet/html/#ip-addresses-part-deux
This works:
struct sockaddr_in sa;
struct sockaddr_in6 sa6;
int e1 = inet_pton(AF_INET, "10.12.110.57", &(sa.sin_addr)); // IP4
int e2 = inet_pton(AF_INET6, "2001:db8:63b3:1::3490", &(sa6.sin6_addr)); // IP6
// Example for IPv4 string
char ip4[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(sa.sin_addr), ip4, INET_ADDRSTRLEN);
printf("The IPv4 address is %s\n", ip4);
// Example for IPv6 string
char ip6[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &(sa6.sin6_addr), ip6, INET6_ADDRSTRLEN);
printf("The Ipv6 address is %s\n", ip6);
Output:
The IPv4 address is 10.12.110.57
The Ipv6 address is 2001:db8:63b3:1::3490
Upvotes: 2
Reputation: 318638
Use inet_ntop()
to convert it to a string
This function converts the network address structure src in the af address family into a character string. The resulting string is copied to the buffer pointed to by dst, which must be a non-null pointer. The caller specifies the number of bytes available in this buffer in the argument size.
inet_ntop() extends the inet_ntoa(3) function to support multiple address families, inet_ntoa(3) is now considered to be deprecated in favor of inet_ntop().
Upvotes: 13