I am reading Beej's guide to network programming and in chapter 5.1, in the showip.c program I see the following line of code:
memset(&hints, 0, sizeof hints);
After a discussion on the ##c channel on freenode I deducted that the reasoning of that memset call could be to set the value of hints.ai_flags to 0(note that the program works fine I remove that line and I explicitly initialize hints.ai_flags to 0). If this is true, why does he need to set the whole struct to 0?
This is the full source:
/*
** showip.c -- show IP addresses for a host given on the command line
*/
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main(int argc, char *argv[])
{
struct addrinfo hints, *res, *p;
int status;
char ipstr[INET6_ADDRSTRLEN];
if (argc != 2) {
fprintf(stderr,"usage: showip hostname\n");
return 1;
}
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // AF_INET or AF_INET6 to force version
hints.ai_socktype = SOCK_STREAM;
if ((status = getaddrinfo(argv[1], NULL, &hints, &res)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
return 2;
}
printf("IP addresses for %s:\n\n", argv[1]);
for(p = res;p != NULL; p = p->ai_next) {
void *addr;
char *ipver;
// get the pointer to the address itself,
// different fields in IPv4 and IPv6:
if (p->ai_family == AF_INET) { // IPv4
struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
addr = &(ipv4->sin_addr);
ipver = "IPv4";
} else { // IPv6
struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
addr = &(ipv6->sin6_addr);
ipver = "IPv6";
}
// convert the IP to a string and print it:
inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
printf(" %s: %s\n", ipver, ipstr);
}
freeaddrinfo(res); // free the linked list
return 0;
}
It's required by getaddrinfo() function documentation (where you pass your hints variable as parameter). From man getaddrinfo:
All the other fields in the structure pointed to by hints must contain either 0 or a NULL pointer, as appropriate.
It's because you are only going to fill/use/initialize some of the fields of the struct, giving 0 to the other fields prevents reading an uninitialzied variable, and sometimes 0 is the default value for those variables.
note that the program works fine I remove that line and I explicitly initialize hints.ai_flags to 0
Not necessarily, if you are on linux, I suggest using valgrind to detect reads to uninitialized variables, since that causes undefined behavior, the behavior could be that nothing wierd happens.
Related
Can someone help me to get the IPs of google.com?
I can't find any good resource on this.
Most tutorials on C network programming create a client socket and a server socket on the same computer. (I don't know in which situation that would make sense)
And none of the codes on beej.us worked for me.
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
int main(void)
{
struct addrinfo* res = NULL;
getaddrinfo("google.com", "443", 0, &res);
struct addrinfo* i;
for(i=res; i!=0; res=res->ai_next)
{
printf("%s\n", res->ai_addr->sa_data);
}
}
Output:
�
�
�
���$u
���$u
���$u
���"u
���"u
���"u
��� u
��� u
��� u
���&u
���&u
���&u
Segmentation fault
First, you never modify i inside of the loop so you end up with an infinite loop. You need to change to loop statement to:
for(i=res; i!=NULL; i=i->ai_next)
Regarding the output, the ai_addr field is of type struct sockaddr *, which is a pointer to a generic socket address struct, and its sa_data field is just a binary blob of the data for that address, not a printable string.
To print these values correctly, you need to inet_ntop function. First, you need to inspect ai_addr->sa_family to see if it is an IPv4 address or an IPv6 address. Then you'll need to cast ai_addr to either a struct sockaddr_in * for IPv4 or struct sockaddr_in6 * for IPv6, then pass the sin_addr or sin6_addr field respectively to inet_ntop along with the address family to convert it to a string.
for(i=res; i!=NULL; i=i->ai_next)
{
char str[INET6_ADDRSTRLEN];
if (i->ai_addr->sa_family == AF_INET) {
struct sockaddr_in *p = (struct sockaddr_in *)i->ai_addr;
printf("%s\n", inet_ntop(AF_INET, &p->sin_addr, str, sizeof(str)));
} else if (i->ai_addr->sa_family == AF_INET6) {
struct sockaddr_in6 *p = (struct sockaddr_in6 *)i->ai_addr;
printf("%s\n", inet_ntop(AF_INET6, &p->sin6_addr, str, sizeof(str)));
}
}
Output:
172.217.10.238
172.217.10.238
172.217.10.238
2607:f8b0:4006:813::200e
2607:f8b0:4006:813::200e
2607:f8b0:4006:813::200e
In This statement i is never being modified in loop body, and because it is not initialized, it never even enters the loop:
for(i=res; i!=0; res=res->ai_next)
{
printf("%s\n", res->ai_addr->sa_data);
}
Additionally, you are missing a few other parts. The following steps are part of a full example linked below:
Create the following instances of struct addrinfo:
struct addrinfo *result = NULL;
struct addrinfo *ptr = NULL;
struct addrinfo hints;
Then initialize Winsock
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
Setup the hints address info structure
ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
Call getaddrinfo
dwRetval = getaddrinfo(argv[1], argv[2], &hints, &result);
if ( dwRetval != 0 ){//handle error}
Now, for example based on above, your loop would look like:
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {//
Entering "www.google.com" 0 on the command line for the complete example (linked below) will look similar to this:
This full Windows example is here. Note: Bug in code, i.e. ptr->ai_cannonname can be null with "www.google.com" so change this line to test before calling:
if(ptr->ai_canonname) printf("\tCanonical name: %s\n", ptr->ai_canonname);
A full Linux example is here.
I'm writing a client side as part of a TCP client server program.
My code reaches the connect part and throws an Invalid argument error, I have gone through the code several times and I couldn't find the problem.
The code receives 3 arguments, first one is an IP address or a hostname, second one is port and the third is the maximum length of the message to be sent.
My code uses getaddrinfo in order to convert the ip address or hostname, creates the needed variables, starts a connection, read from file, send data and receive data.
I run the code with:
gcc -std=gnu99 -O3 -Wall -o pcc_client pcc_client.c
./pcc_client 127.0.0.1 2233 4
The output is:
sockaddr_in initialized
Error starting connection : Invalid argument
#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <dirent.h>
#define FILE_ADDR "/dev/urandom"
int main(int argc, char *argv[]) {
if (argc != 4) {
printf("should receive 3 arguments Received %d args\n", argc);
exit(1);
}
//Get command line arguments
unsigned int port = atoi(argv[2]);
int length = atoi(argv[3]); //Number of bytes to read
char* buffer = malloc(length * sizeof(char)); //Buffer to hold data read from file
char* recvBuf = malloc(10 * sizeof(char)); // Buffer to hold response from server
struct addrinfo hints, *servinfo, *p;
struct sockaddr_in *serv_addr;
int rv;
char ip[100];
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo(argv[1], argv[2], &hints, &servinfo)) != 0) {
perror("getaddrinfo error\n");
return 1;
}
for (p = servinfo; p != NULL; p = p->ai_next) {
serv_addr = (struct sockaddr_in *) p->ai_addr;
strcpy(ip, inet_ntoa(serv_addr->sin_addr));
}
// inet_aton(ip, &h.sin_addr);
freeaddrinfo(servinfo);
//Initialize socket
int sockfd;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) //Error creating socket
{
perror("Error creating socket \n");
exit(1);
}
printf("socket created\n");
//Initialize sockaddr_in structure
memset((void*)serv_addr, 0,(size_t) sizeof(*serv_addr));
serv_addr->sin_family = AF_INET;
serv_addr->sin_port = htons(port);
serv_addr->sin_addr.s_addr = inet_addr("127.0.0.1"); //change?
//Initialize connection
if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { //Error connecting
perror("Error starting connection \n");
exit(1);
}
printf("connect succesful\n");
exit(0);
}
You are using serv_addr all wrong.
You have declared serv_addr as a sockaddr_in* pointer. After getaddrinfo() exits successfully, you are looping through the output list, assigning serv_addr to point at every ai_addr in the list, and then you free the list, leaving serv_addr pointing at invalid memory. You then trash memory when you try to populate serv_addr with data. And then you end up not even passing a valid pointer to a sockaddr_in to connect() at all, you are actually passing a pointer to a pointer to a sockaddr_in, which is why it complains about an "invalid argument".
In fact, you are going about this situation all wrong in general. When using getaddrinfo(), since it returns a linked list of potentially multiple socket addresses, you need to loop through the list attempting to connect() to every address until one of them is successful. This is especially important if you ever want to upgrade the code to support both IPv4 and IPv6 (by setting hints.ai_family = AF_UNSPEC;).
Try something more like this instead:
int main(int argc, char *argv[])
{
if (argc != 4)
{
printf("should receive 3 arguments Received %d args\n", argc);
exit(1);
}
struct addrinfo hints, *servinfo, *p;
int sockfd = -1;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET; // or AF_UNSPEC
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
int rv = getaddrinfo(argv[1], argv[2], &hints, &servinfo);
if (rv != 0)
{
perror("getaddrinfo error\n");
return 1;
}
for (p = servinfo; p != NULL; p = p->ai_next) {
//Initialize socket
sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (sockfd < 0) continue;
//Initialize connection
rv = connect(sockfd, p->ai_addr, (socklen_t) p->ai_addrlen);
if (rv == 0) break;
close(sockfd);
sockfd = -1;
}
freeaddrinfo(servinfo);
if (sockfd < 0) //Error creating/connecting socket
{
perror("Error creating/connecting socket \n");
exit(1);
}
printf("connect successful\n");
...
close(sockfd);
exit(0);
}
You define serv_addr
struct sockaddr_in *serv_addr;
Then you use it
memset((void*)serv_addr, 0,(size_t) sizeof(*serv_addr));
serv_addr->sin_family = AF_INET;
serv_addr->sin_port = htons(port);
serv_addr->sin_addr.s_addr = inet_addr("127.0.0.1"); //change?
But nowhere in between those two places in the code do you initialize the pointer! That means serv_addr is uninitialized and its value is indeterminate and will point to some seemingly random location. Dereferencing the pointer will lead to undefined behavior.
The simple and natural and de facto standard solution is to make serv_addr not a pointer, but a structure object:
struct sockaddr_in serv_addr;
Then when you need a pointer you use the address-of operator &.
The issue above is further complicated by you actually using the & operator when calling connect. With serv_addr being a pointer, then &serv_addr is a pointer to the pointer. It will be of type struct sockaddr_in **. It is this issue, with the pointer to the pointer, that leads to the error message, since the pointer you send in is not a pointer to a sockaddr_in structure object.
By using a structure object as shown above will solve this problem as well.
I'm trying to send a UDP packet in C. I have the following sendto():
char* msg = "Hello";
//ret is the return value of getaddrinfo, the address is AF_INET (IPv4)
//and the sock_type is SOCK_DGRAM (UDP)
struct sockaddr_in *ip = (struct sockaddr_in *)ret->ai_addr;
if ((sendto(sock, msg, strlen(msg), 0, (struct sockaddr *)ip,
sizeof(struct sockaddr *))) != -1) {
printf("msg sent successfully");
} else {
printf("Error sending msg: %s\n", strerror(errno));
}
However, it's returning an error saying there's an invalid argument. Looking at the manpage I can't really tell which one is the invalid argument. Any ideas?
EDIT: Here's all my code
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <errno.h>
int main(int argc, const char *argv[])
{
/*
* Help the technically challenged among us who have no idea
* what on God's green Earth they are doing with this thing.
*/
if (argc != 2) {
printf("usage: routetracer <ip address or hostname>\n");
return -1;
}
/*
* hints- parameters for return value of getaddrinfo
* ret- return value of getaddrinfo
*/
struct addrinfo hints, *ret;
int status;
char ipv4[INET_ADDRSTRLEN];
int ttl = 0;
char* msg = "Hello";
int last_hop = 0;
//define what we want from getaddrinfo
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET; //IPv4
hints.ai_socktype = SOCK_DGRAM; //UDP packets
//call getaddrinfo to fill ret, w/ error chk
if ((status = getaddrinfo(argv[1], NULL, &hints, &ret)) != 0) {
printf("getaddrinfo: %s\n", gai_strerror(status));
return -1;
}
//extract IPv4 address from ret
struct sockaddr_in* ip = (struct sockaddr_in *)ret->ai_addr;
//convert address from pure numbers to something easier to read
inet_ntop(ret->ai_family, &(ip->sin_addr), ipv4, INET_ADDRSTRLEN);
//kindly inform the user of which hostname they are connecting to
printf("Route for: %s\n", ipv4);
//create a socket
int sock = socket(ret->ai_family, ret->ai_socktype, ret->ai_protocol);
ttl = 1;
if ((setsockopt(sock, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl))) != -1) {
printf("TTL set successfully\n");
} else {
printf("Error setting TTL: %s\n", strerror(errno));
}
if ((sendto(sock, msg, strlen(msg), 0, ret->ai_addr,
ret->ai_addrlen)) != -1) {
printf("msg sent successfully");
} else {
printf("Error sending msg: %s\n", strerror(errno));
}
return 0;
}
Running the program gives the following output:
$ ./routetracer www.google.com
Route for: 173.194.46.82
TTL set successfully
Error sending msg: Invalid argument
Try:
if ((sendto(sock, msg, strlen(msg), 0, (struct sockaddr *)ip,
sizeof(struct sockaddr_in))) != -1) {
You're giving it the size of a pointer, not the size of the structure. And it needs to be the specific structure type, not the generic type.
As Barmar points out, one reason for the EINVAL is the incorrect:
sizeof(struct sockaddr *)
which gives the size of a pointer. See Socket programming: sendto always fails with errno 22 (EINVAL).
The second reason seems to be sin_port, which getaddrinfo returns as 0. Changing it to 80 say clears up the EINVAL, as in:
((struct sockaddr_in *)ret->ai_addr)->sin_port = htons(80); // test
Here port 80 here is not HTTP, but instead (for UDP) is Google's experimental QUIC Chromium.
Wikipedia http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers states that Port 0 is for UDP reserved, and for TCP is unofficially reserved as a "programming technique for specifying system-allocated (dynamic) ports".
And as an aside (and referring to the original question), you may not need bother with the variable ip. You are casting ret->ai_addr to struct sockaddr_in *, and then back again to its original type.
And, as Remy Lebeau points out, it is better to use the service parameter of getaddrinfo. So putting this all together, your code could look more like:
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET; //IPv4
hints.ai_socktype = SOCK_DGRAM; //UDP packets
if ((status = getaddrinfo(argv[1], "80", &hints, &ret)) != 0) {
printf("getaddrinfo: %s\n", gai_strerror(status));
return -1;
}
assert(ret->ai_family == AF_INET); // guaranteed
assert(ret->ai_socktype == SOCK_DGRAM); // guaranteed
assert(((struct sockaddr_in *)ret->ai_addr)->sin_port == htons(80)); // guaranteed
// ...
if ((sendto(sock, msg, strlen(msg), 0, ret->ai_addr, ret->ai_addrlen)) != -1) {
// ...
/* program to print the IP address of the Host*/
------------------------------------------------
I am trying to print the Host IP address. when I execute the following program
I am getting loop back address that is 127.0.0.1. What should I change to get the
actual IP address.
# include <stdio.h>
# include <stdlib.h>
# include <arpa/inet.h>
# include <string.h>
# include <sys/types.h>
# include <sys/socket.h>
# include <netdb.h>
# include <netinet/in.h>
int main () {
void *addr;
char ipstr[INET6_ADDRSTRLEN];
int rv;
struct addrinfo hints, *res, *p;
memset ( &hints, 0, sizeof hints );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
//hints.ai_flags = AI_ADDRCONFIG;
hints.ai_flags = AI_PASSIVE;
if ((rv = getaddrinfo(NULL ,"3490" , &hints, &res)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
for(p = res;p != NULL; p = p->ai_next) {
struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
addr = &(ipv4->sin_addr);
inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
printf(" %s\n", ipstr);
}
}
As long as your development machine is not connected to a network you'll get the loopback address (which is perfectly valid for local network, of course). As soon as you connect the machine to the network you can determine the "right" address.
ipconfig, btw, behaves the same.
If you call getaddrinfo with NULL for the node name (first parameter) it is the same as when you call it with "localhost". You'll get the loopback IP. However, if you use the "real" hostname, you'll get the "real" ip.
I am trying to resolve a URL's IP address using getaddrinfo(), but it always returns the wrong IP address, I have tried with several URL's and the result is same. any help wold be greatly appreciated.
The program returnes the ip address : 209.85.175.99 insted of returning the real IP which is 74.125.39.147
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
int
main()
{
char *hostname = "www.google.lk";
struct addrinfo hints, *res;
struct in_addr addr;
int err;
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = AF_INET;
if ((err = getaddrinfo(hostname, NULL, &hints, &res)) != 0) {
printf("error %d\n", err);
return 1;
}
addr.s_addr = ((struct sockaddr_in *)(res->ai_addr))->sin_addr.s_addr;
printf("ip address : %s\n", inet_ntoa(addr));
freeaddrinfo(res);
return 0;
}
google.com can resolve to different IP addresses depending on your own location. It's kind of load balancing trick.