In C does the function inet_pton() convert only the ip address from printble to string format or it also converts ip address and port number too? I mean, if I have a string of format A.B.C.D:E where A.B.C.D is the ip and E is the port number, would I be able to use inet_pton for the same?
3 Answers
No, it does not handle port numbers. The man page specifies exactly what it expects for IPv4 addresses:
src
points to a character string containing an IPv4 network address in dotted-decimal format, "ddd.ddd.ddd.ddd", where ddd is a decimal number of up to three digits in the range 0 to 255. The address is converted to astruct in_addr
and copied todst
, which must besizeof(struct in_addr)
(4) bytes (32 bits) long.

- 349,597
- 67
- 533
- 578
You have to split off the port number yourself. This is rather problematic since the way you go about doing that depends on whether the address is ipv4 or ipv6. I believe this issue is the reason many unix utilities use a -p
option instead of the :port
syntax to specify port.

- 208,859
- 35
- 376
- 711
Use getaddrinfo()
the swiss knife of the address conversion.

- 5,277
- 1
- 23
- 39
-
1This is good advice but you still have to split off the port number yourself. – R.. GitHub STOP HELPING ICE Jan 25 '13 at 20:52