GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 11-Aug-2005, 05:03
Kjeksen Kjeksen is offline
Junior Member
 
Join Date: May 2005
Posts: 57
Kjeksen is on a distinguished road

Socket programming structures


Howdy! I have some questions about the socket programming structures.

CPP / C++ / C Code:

#include <stdio.h>
    #include <stdlib.h>
    #include <errno.h>
    #include <netdb.h>
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>

    int main(int argc, char *argv[])
    {
        struct hostent *h;

        if (argc != 2) {  // error check the command line
            fprintf(stderr,"usage: getip address\n");
            exit(1);
        }

        if ((h=gethostbyname(argv[1])) == NULL) {  // get the host info
            herror("gethostbyname");
            exit(1);
        }

        printf("Host name  : %s\n", h->h_name);
        printf("IP Address : %s\n", inet_ntoa(*((struct in_addr *)h->h_addr)));
       
       return 0;
    } 

Now. Here is a "simple" program from Beej`s guide to network programming. As u see, there is a struct pointer. Where is that pointing to!? I haven`t made a structure. Now, maybe im asking a bit silly questions but, i havent even made a structure. Is that structure somewhere in the header?
Can someone show me how it works and give me some basic explenation on how this is working?
  #2  
Old 11-Aug-2005, 07:04
LuciWiz's Avatar
LuciWiz LuciWiz is offline
Moderator
 
Join Date: Jul 2004
Location: Cluj-Napoca (Romania)
Posts: 894
LuciWiz is a jewel in the roughLuciWiz is a jewel in the roughLuciWiz is a jewel in the roughLuciWiz is a jewel in the rough
Quote:
Originally Posted by Kjeksen
Now. Here is a "simple" program from Beej`s guide to network programming. As u see, there is a struct pointer. Where is that pointing to!? I haven`t made a structure. Now, maybe im asking a bit silly questions but, i havent even made a structure. Is that structure somewhere in the header?
Can someone show me how it works and give me some basic explenation on how this is working?

The structure should be defined in the header, yes. I suppose netdb.h is that header (winsock.h on Windows) If you look closely at "Beej's Guide", you'll see he shows the structure of the structure

Quote:
Originally Posted by Brian "Beej" Hall
As you see, it returns a pointer to a struct hostent, the layout of which is as follows:

struct hostent {
char *h_name;
char **h_aliases;
int h_addrtype;
int h_length;
char **h_addr_list;
};
#define h_addr h_addr_list[0]

The memory allocation is (or should be) done in the gethostbyname function.
Now, I'm not a C expert, but I'm pretty sure that he's example is flawed. There is no memory freeing what so ever... Of course it will be done by the system when the program ends, but this is not the proper way to write a program if you ask me. I suppose he wanted his guide to be easier on beginners, but teaching incomplete techniques may be worst than not teaching them at all...
If anybody has a different opinion, please correct me. The link for this part of the guide is: Guide

Best regards,
Lucian
__________________
Please read these Guidelines before posting on the forum

"A person who never made a mistake never tried anything new."
Einstein
  #3  
Old 11-Aug-2005, 08:12
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,712
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold
Quote:
Originally Posted by LuciWiz
.
The memory allocation is (or should be) done in the gethostbyname function.
.

The function gethostbyname() (and others: gethostbyaddr(), getservbyname(), getservbyport()) typically returns a pointer to a static structure so you don't need to allocate or de-allocate memory. Unfortunately, for some applications, that means that these functions are not re-entrant, and, therefore are not thread-safe. In fact, the POSIX specification explicitly states that gethostbyname() need not be re-entrant.

Some implementations (gcc for Linux, for example) have functions gethostbyname_r() and gethostbyaddr_r() that are re-entrant (you pass a pointer to enough memory to hold everthing). As far as I know (and I could be wrong) there are no standards for the _r functions --- look on the man pages for your system to see what's up with them. I have not seen any of the _r functions in any headers for Windows compilers that I have (including cygwin/gcc).

Regards,

Dave
  #4  
Old 11-Aug-2005, 08:13
Kjeksen Kjeksen is offline
Junior Member
 
Join Date: May 2005
Posts: 57
Kjeksen is on a distinguished road
Thanks alot

But im having trouble with all the use of pointers in socket programming, and it would help me if someone could transform this into "human language"

CPP / C++ / C Code:
inet_ntoa(*(struct in_addr *)h-> h_addr);

Now am i right on this one:

inet_ntoa is a function to return your ip address.
starts with pointing at a structure called in_addr wich is defined inside a header file. And then points at eh, im not sure how this -> works.
  #5  
Old 11-Aug-2005, 09:04
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,712
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold
Quote:
Originally Posted by Kjeksen
Thanks alot

But im having trouble with all the use of pointers in socket programming, and it would help me if someone could transform this into "human language"

CPP / C++ / C Code:
inet_ntoa(*(struct in_addr *)h-> h_addr);

Now am i right on this one:

inet_ntoa is a function to return your ip address.
starts with pointing at a structure called in_addr wich is defined inside a header file. And then points at eh, im not sure how this -> works.

You can try to work from the inside out. First of all, what is h?

CPP / C++ / C Code:
        struct hostent *h;

So h is a pointer to a struct hostent.

Somewhere in the header files (netdb.h, I think) there is the definition of hostent. It looks something like this:

CPP / C++ / C Code:
struct  hostent {
        const char      *h_name;        /* official name of host */
        char    **h_aliases;    /* alias list */
        int     h_addrtype;     /* host address type */
        int     h_length;       /* length of address */
        char    **h_addr_list;  /* list of addresses from name server */
#define h_addr  h_addr_list[0]  /* address, for backward compatiblity */
};

Now, the notation h->haddr is shorthand for (*h).h_addr (that is, it is the member of the struct pointed to by h). You had better get used to it, because the -> is ubiquituous.

So h->h_addr is a pointer to the beginning of h_addr_list (h_addr_list is a pointer to an array of addresses).

Now, we want to pass the string corresponding to this address to the function inet_ntoa. Now the argument to inet_ntoa() is an in_addr structure (note: not a pointer to struct, but a struct). To make a long story short, the first, and only, member of the struct we send to inet_ntoa() has the type in_addr_t, which is a pointer to the address that we want inet_ntoa to resolve for us.

Here's how it breaks down:

This is a pointer to the address
CPP / C++ / C Code:
h->h_addr

This makes it look like a pointer to an in_addr structure:
CPP / C++ / C Code:
(struct in_addr *)h->h_addr

Now, this makes it an in_addr struct:
CPP / C++ / C Code:
*((struct in_addr *)h->haddr)

That becomes the argument of inet_ntoa.

Result (using the exact code you posted):
Quote:
$> gcc -o test test.c
$> test localhost.localdomain
Host name : localhost.localdomain
IP Address : 127.0.0.1

Regards,

Dave

Postscript: There are two ways that I could have approached the problem (there are, obviously more than two ways to approach the problem, but only two ways that I would have used).

Top-down: Start with inet_ntoa(). See what kind of argument it requires, and figure out what it will do with it. Try to figure out how to get that from what it has to work with.

Bottom-up: Start with h. See what is being done with it (->, casting result to another type of pointer, etc.)

Sometimes when I am actually writing code, I think that I am, maybe, the last Bottom-up guy in a Top-down world, but that's how I usually try to see things. Or rather: Top-down for design. Bottom-up for implementation and, especially, for analysis.

You see, when you start from the top, there are lots of branches. Like a good detective story: false clues and red herrings that cause you to backtrack. Good for your reading enjoyment, and probably good for creative design, but kind of frustrating when you really need to get to the bottom of things (and you already know what the bottom has to be).

On the other hand, starting at the bottom, you have something definite to start with. Regardless of how many ways to get there, you are there. Then go up to the next level, etc.
  #6  
Old 11-Aug-2005, 15:02
Kjeksen Kjeksen is offline
Junior Member
 
Join Date: May 2005
Posts: 57
Kjeksen is on a distinguished road
Thanks alot. This helped me much. And it made me realize that i have to learn more about structure pointers and linked list ( i think its called? -> )

Again. Thanks for nice replys
  #7  
Old 12-Aug-2005, 00:50
LuciWiz's Avatar
LuciWiz LuciWiz is offline
Moderator
 
Join Date: Jul 2004
Location: Cluj-Napoca (Romania)
Posts: 894
LuciWiz is a jewel in the roughLuciWiz is a jewel in the roughLuciWiz is a jewel in the roughLuciWiz is a jewel in the rough
Quote:
Originally Posted by davekw7x
The function gethostbyname() (and others: gethostbyaddr(), getservbyname(), getservbyport()) typically returns a pointer to a static structure so you don't need to allocate or de-allocate memory.

Thanks, I didn't even think about that!
To be honest, I don't like it, but what do I know

Best regards,
Lucian
__________________
Please read these Guidelines before posting on the forum

"A person who never made a mistake never tried anything new."
Einstein
  #8  
Old 14-Aug-2005, 10:39
Kjeksen Kjeksen is offline
Junior Member
 
Join Date: May 2005
Posts: 57
Kjeksen is on a distinguished road
what use do we have from argc and argv?
  #9  
Old 14-Aug-2005, 11:12
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,712
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold
Quote:
Originally Posted by Kjeksen
what use do we have from argc and argv?

The int argc tells us how many things were entered on the command line.
if argc == 1, then only the program name was entered; if argc > 1, then other arguments are available. The variable argv is an array of pointers to char. Each pointer to char is treated as a "string" in C (there is no such thing as a "string" data type).

A "C-style string" is a sequence of chars terminated by a zero byte. This construct is a fundamental part of C language library function implementations. But don't let the terminology confuse you; there is no such thing as a "string" data type in the C language.

All standard C library "string" functions operate on this type of construct. This includes strcpy(), strcat(), strlen(), etc. Also things like fgets(), and printf() with %s format specifier. "String" arguments to these functions are "pointer to char".

Did I mention previously that if you want to get anywhere in C you just gotta glom onto the concept of pointers and look at lots of examples of their uses? Oh, yeah, I guess I did.

Note that in C++ there is a "string" class that is part of the Standard C++ library. It is quite a different animal, and has lots of interesting and useful characteristics not available in C.

Note, also, that in the Microsoft Foundation Class, there is a Cstring variable type. This is a special data type, not (not) the same thing as I am referring to here as a "C-style string". One more time: there is no such thing as a "string" data type in the C language.


Let's stick to C for now.

For example, the program is invoked with the host name as argv[1].

You can try this:

CPP / C++ / C Code:
#include <stdio.h>
int main(int argc, char *argv[])
{
  int i;
  printf("argc = %d\n", argc);

  for (i = 0; i < argc; i++) {
    printf("argv[%d]: <%s>\n", i, argv[i]);
  }
  return 0;
}

I named the program source file "testargs.c"

Then, on my Linux system:

Quote:
$ gcc -o testargs testargs.c
$ ./testargs This is a test
argc = 5
argv[0]: <./testargs>
argv[1]: <This>
argv[2]: <is>
argv[3]: <a>
argv[4]: <test>
$

Try it with other things on the command line:

Quote:
./testargs localhost.localdomain

./testargs "This is" a "Test" 96Ucabcx33 44

Regards,

Dave
  #10  
Old 14-Aug-2005, 12:48
Kjeksen Kjeksen is offline
Junior Member
 
Join Date: May 2005
Posts: 57
Kjeksen is on a distinguished road
Well, i know when you start the program then argv[0], will automaticly be the location and name of file. Something like this: C:\dev-cpp\test.cpp ( Yes i have windows ) But here is one "strange" thing im wondering about.

I have looked more on the code examples to beej`s guide, and getting closer to understanding alot in the code. But here is a strange thing:
CPP / C++ / C Code:

 if ((he=gethostbyname(argv[1])) == NULL) {  // get the host info 
            perror("gethostbyname");
            exit(1);


how is the host info gathered from this chunk of code? can someone plz explain abit about how this works? the he=gethostbyname(argv[1])) == NULL part really confuses me. What is argv[1] doing there!?
 
 

Recent GIDBlogMeeting the populace by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
[PROGRAM] Winsock Programming Max Payne MS Visual C++ / MFC Forum 1 08-Mar-2007 23:38
windows sockets confusion ubergeek C++ Forum 1 18-Jul-2005 20:44
socket programming pointer C++ Forum 1 10-May-2005 15:53
write a function in socket programming dxgn C++ Forum 0 07-Jan-2005 08:48
GUI programming crystalattice C++ Forum 5 14-Sep-2004 12:17

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 11:25.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.