3

can i convert string to ip address in c + + on multiple platforms Windows (various versions) and Unix systems?

2
  • What excatly do you need ... you have to convert a string to astring formatted in this way xxx.xxx.xxx.xxx ? Commented 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 ...? Commented Mar 21, 2011 at 13:36

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

5 Comments

I have to write code that works for both Windows and UNIX systems. This can not know before. How to change this code?
What must i is include in order to use this code on both Windows and Unix systems?
@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__.
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
From memory, I think you need to include winsock2.h before windows.h. (Also I think winsock2.h and winsock.h are incompatible, so watch out for that too! - it's a real pain the first time you try this stuff.)
0

If you have a hostname or FQDN and you need a DNS query or internal host list query to translate it to an IP Address, then you need to use gethostbyname.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.