can i convert string to ip address in c + + on multiple platforms Windows (various versions) and Unix systems?
-
What excatly do you need ... you have to convert a string to astring formatted in this way xxx.xxx.xxx.xxx ?Kevin– Kevin2011-03-21 13:16:30 +00:00Commented Mar 21, 2011 at 13:16
-
It's unclear exactly what you want. What is this string? A host name or an IP address, or ...?Brian Neal– Brian Neal2011-03-21 13:36:08 +00:00Commented Mar 21, 2011 at 13:36
Add a comment
|
2 Answers
You can use the inet_addr() function to convert an IP address represented as a string into the form that can be used with other socket functions.
Here's an example use (taken from here):
int rc;
int s;
struct sockaddr_in myname;
/* clear the structure to be sure that the sin_zero field is clear */
memset(&myname, 0, sizeof(myname));
myname.sin_family = AF_INET;
myname.sin_addr = inet_addr("129.5.24.1");
/* specific interface */
myname.sin_port = htons(1024);
5 Comments
Safari
I have to write code that works for both Windows and UNIX systems. This can not know before. How to change this code?
Safari
What must i is include in order to use this code on both Windows and Unix systems?
ereOn
@GgSalent: The includes differ for Windows and *NIX. On Windows its likely to be
<winsock2.h> and on *NIX <sys/socket.h>. You can still provide a "portable" code using preprocessor conditions like: #ifdef __WIN32__.Safari
I did this but I have a lot of mistakes .. I have included everything? I use Windows XP at this time #ifdef WIN32 #include <windows.h> #include <winsock2.h> #else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #endif