Winsock - How to get the IP of connected sockets.

So I have this server program and I want to get the IP of my cleint sockets, kinda like this:

1
2
3
if((ATemp = accept(server,(sockaddr *)&addr,NULL)) != INVALID_SOCKET){
ioctlsocket(ATemp,FIONBIO,&iMode);
cout<<"IP: "<<addr.sin_addr.s_addr<<"\n";


Where the program would display "IP: " then the connecting computers IP. But that dosn't work, so can someone explain to me how to do this?
Copy and pasted from my TCP connection class:

1
2
3
4
5
    #ifdef __linux__
    unsigned long getIP() const {return address.sin_addr.s_addr;}
    #else
    unsigned long getIP() const {return (address.sin_addr.S_un.S_un_b.s_b1<<24)|(address.sin_addr.S_un.S_un_b.s_b2<<16)|(address.sin_addr.S_un.S_un_b.s_b3<<8)|address.sin_addr.S_un.S_un_b.s_b4;}
    #endif 
Is that some strange way of defining a function?
How do I get it into a char/string?
EDIT: Pasting that code into my program generates a syntax error.
Last edited on
Duh, it's taken from a class declaration, like I said.
You'll have to modify it according to your own purposes.

A way to convert it to a string (also taken from a class, IP would be the number returned by getIP):
1
2
std::string toString() const {return IntToStr(IP>>24)+"."+IntToStr((IP&16777215)>>16)+"."+
                                     IntToStr((IP&65535)>>8)+"."+IntToStr(IP&255);}


1
2
3
4
5
6
std::string IntToStr (int value)
{
  char buf[20];
  sprintf(buf,"%i",value);
  return buf;
}
1
2
3
4
5
6
std::string IntToStr (int value)
{
  char buf[20];
  sprintf(buf,"%i",value);
  return buf;
}


Ew...

1
2
3
4
5
6
template <typename T>
std::string to_string(T item) {
    std::stringstream ret;
    ret<<item;
    return ret.str();
}
I don't use any of the standard stream classes in my projects (except for console applications that are just meant for private use).
They increase executable size by ~500 KB when compiling with MinGW and I have no need for them as I have my own convenience functions like IntToStr plus boost::lexical_cast (although lexical_cast also has noticeable overhead) and custom file stream classes.
Both sprintf and lexical_cast are several times faster than a stringstream solution, by the way.
You are probably statically linking them:

http://www2.research.att.com/~bs/bs_faq.html#Hello-world

If you know they are going to be there when you run the program, don't.
Yes, MinGW statically links libstdc++. There's no easy way around that, but at least this makes sure most of your programs will run on all Windows systems out-of-the-box (even Win9x).
As I said, the stream classes provide no additional benefit to me anyway, so that suits me just fine.

Even though that's true for me, it shouldn't keep anyone else from using the stream classes.
Topic archived. No new replies allowed.