What is the difference between AF_INET and PF_INET in socket programming?
I'm confused between using AF_INET and PF_INET in socket()
and bind()
.
Also, how to give ip-address in sin_addr
field?
What is the difference between AF_INET and PF_INET in socket programming?
I'm confused between using AF_INET and PF_INET in socket()
and bind()
.
Also, how to give ip-address in sin_addr
field?
Beej's famous network programming guide gives a nice explanation:
In fact, AF_ and PF_ are the same thing. There are some words on Wikipedia will clear your confusion
There are situations where it matters.
If you pass AF_INET to
socket()
in Cygwin, your socket may or may not be randomly reset. Passing PF_INET ensures that the connection works right.Cygwin is self-admittedly a huge mess for socket programming, but it is a real world case where AF_INET and PF_INET are not identical.
I found in Linux kernel source code that PF_INET and AF_INET are the same. The following code is from file include/linux/socket.h, line 204 of Linux kernel 3.2.21 tree.
AF_INET = Address Format, Internet = IP Addresses
PF_INET = Packet Format, Internet = IP, TCP/IP or UDP/IP
AF_INET is the address family that is used for the socket you're creating (in this case an Internet Protocol address). The Linux kernel, for example, supports 29 other address families such as UNIX sockets and IPX, and also communications with IRDA and Bluetooth (AF_IRDA and AF_BLUETOOTH, but it is doubtful you'll use these at such a low level).
For the most part sticking with AF_INET for socket programming over a network is the safest option.
Meaning, AF_INET refers to addresses from the internet, IP addresses specifically.
PF_INET refers to anything in the protocol, usually sockets/ports.
Meaning,
AF_INET
refers to addresses from the internet, IP addresses specifically.PF_INET
refers to anything in the protocol, usually sockets/ports.Consider reading the man pages for socket(2) and bind(2). For the
sin_addr
field, just do something like the following to set it: