0

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?

TheRookierLearner
  • 3,643
  • 8
  • 35
  • 53

3 Answers3

3

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 a struct in_addr and copied to dst, which must be sizeof(struct in_addr) (4) bytes (32 bits) long.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
3

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.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
1

Use getaddrinfo() the swiss knife of the address conversion.

Yann Droneaud
  • 5,277
  • 1
  • 23
  • 39