polslinux
polslinux

Reputation: 1779

understand a C socket instruction

This is a statement that I haven't completely understood.

serv_addr.sin_addr.s_addr = ((struct in_addr*)(hp->h_addr)) -> s_addr;

Does this mean that:

  1. i put hp into h_addr
  2. typecast of type struct in_addr* of hp->h_addr
  3. all of this have been copied into s_addr

So serv_addr.sin_addr.s_addr contain the hostname and the ip address of choosen host.
Is this right?
(PS: hp is struct hostent *hp ; hp=gethostbyname(argv[1]);)

Upvotes: 0

Views: 150

Answers (2)

ikegami
ikegami

Reputation: 386706

(1) is wrong. hp->h_addr is short for (*hp).h_addr. It's a dereference plus a member selection.

In English, one might say "Copy hp's h_addr into serv_addr's s_addr. This requires a cast."

Upvotes: 2

Dancrumb
Dancrumb

Reputation: 27589

You need to understand the arrow operator.

Essentially, it gives you access to the member of a structure when you have a pointer to that structure.

Thus, hp->h_addr gives you access to the h_addr member of the hostent structure that hp points to. Then, you're casting that member to a in_addr * and dereferencing that so that you can access the s_addr member of the in_addr structure.

Upvotes: 3

Related Questions