PDA

View Full Version : Socket Project (getting one of multiple clients IP)


tal0n
04-04-2003, 01:51 AM
I need to be able to get a clients IP address. I am creating a multiuser chat program for AP Computer Science Class at school and I am using a linked list to store each clients username and IP address in the list when they logon. I am using select() with this and I need to be able to when they begin typing something use a function (already made) to search the list and find their username with a parameter of their IP address only problem is that I don't know how to grab their IP address in a character string.

amutor
04-04-2003, 06:39 AM
Hi,

so I presume you are calling accept() on the server side each time client appears, that means :


char *address;
struct sockaddr_in addr;
unsiged int len=sizeof(struct sockaddr_in);

...

newfd = accept(sock_fd, (struct sockaddr *) &addr, &len );

Sou you have filled addr with struct sockaddr_in from the client, now just call

address = inet_ntoa(addr.sin_addr);

And you will get IP address in standard dot notation in string form into address.

See 'man inet_ntoa'.

Bye.

tal0n
04-04-2003, 10:05 PM
That is good but maybe you misunderstood or I didn't explain it right. I have this part of code that will wait until action is found and gets the text enter and prepares to send it.

// run through the existing connections looking for data to read
for(i = 0; i <= fdmax; i++) {
if (FD_ISSET(i, &read_fds)) { // we got one!!

Within that if there is code to handle a new connection and and else to handle entered text. What I need is if it is not a new connection (someone is entering text) I need to beable to get that person's IP at that moment which will be used as a parameter to a function that searches a linked list for the appropriate username. From there the username is placed as the front of the message and what they say is strcat()ed to the end of the username. I need to know how to get the IP address of the client in which activity is happening.

RobSeace
04-04-2003, 10:55 PM
Well, one method is to call getpeername() on the connected socket...
That'll give you the (raw) IP + port# of the remote peer...

Another would be to store the socket FD in your list where you have
the username and IP, then just use the socket FD as a key to search
on, instead of the IP...

tal0n
04-05-2003, 06:03 PM
Thank you Rob