What is the difference between a port and a socket?
Asked Answered
U

37

1132

This was a question raised by one of the Software Engineers in my organisation. I'm interested in the broadest definition.

Unpopular answered 30/9, 2008 at 10:4 Comment(3)
Just to reiterate, sockets are not limited to network IO. They're available in all sorts of situations for streaming data between various applications.Offcenter
Could you give 2 or 3 examples of non-network IO sockets?Tallu
In the realm of a network socket, a socket object is a communication tunnel dependent on a host IP address and port number to communicate at.Underwing
G
1158

Summary

A TCP socket is an endpoint instance defined by an IP address and a port in the context of either a particular TCP connection or the listening state.

A port is a virtualisation identifier defining a service endpoint (as distinct from a service instance endpoint aka session identifier).

A TCP socket is not a connection, it is the endpoint of a specific connection.

There can be concurrent connections to a service endpoint, because a connection is identified by both its local and remote endpoints, allowing traffic to be routed to a specific service instance.

There can only be one listener socket for a given address/port combination.

Exposition

This was an interesting question that forced me to re-examine a number of things I thought I knew inside out. You'd think a name like "socket" would be self-explanatory: it was obviously chosen to evoke imagery of the endpoint into which you plug a network cable, there being strong functional parallels. Nevertheless, in network parlance the word "socket" carries so much baggage that a careful re-examination is necessary.

In the broadest possible sense, a port is a point of ingress or egress. Although not used in a networking context, the French word porte literally means door or gateway, further emphasising the fact that ports are transportation endpoints whether you ship data or big steel containers.

For the purpose of this discussion I will limit consideration to the context of TCP-IP networks. The OSI model is all very well but has never been completely implemented, much less widely deployed in high-traffic high-stress conditions.

The combination of an IP address and a port is strictly known as an endpoint and is sometimes called a socket. This usage originates with RFC793, the original TCP specification.

A TCP connection is defined by two endpoints aka sockets.

An endpoint (socket) is defined by the combination of a network address and a port identifier. Note that address/port does not completely identify a socket (more on this later).

The purpose of ports is to differentiate multiple endpoints on a given network address. You could say that a port is a virtualised endpoint. This virtualisation makes multiple concurrent connections on a single network interface possible.

It is the socket pair (the 4-tuple consisting of the client IP address, client port number, server IP address, and server port number) that specifies the two endpoints that uniquely identifies each TCP connection in an internet. (TCP-IP Illustrated Volume 1, W. Richard Stevens)

In most C-derived languages, TCP connections are established and manipulated using methods on an instance of a Socket class. Although it is common to operate on a higher level of abstraction, typically an instance of a NetworkStream class, this generally exposes a reference to a socket object. To the coder this socket object appears to represent the connection because the connection is created and manipulated using methods of the socket object.

In C#, to establish a TCP connection (to an existing listener) first you create a TcpClient. If you don't specify an endpoint to the TcpClient constructor it uses defaults - one way or another the local endpoint is defined. Then you invoke the Connect method on the instance you've created. This method requires a parameter describing the other endpoint.

All this is a bit confusing and leads you to believe that a socket is a connection, which is bollocks. I was labouring under this misapprehension until Richard Dorman asked the question.

Having done a lot of reading and thinking, I'm now convinced that it would make a lot more sense to have a class TcpConnection with a constructor that takes two arguments, LocalEndpoint and RemoteEndpoint. You could probably support a single argument RemoteEndpoint when defaults are acceptable for the local endpoint. This is ambiguous on multihomed computers, but the ambiguity can be resolved using the routing table by selecting the interface with the shortest route to the remote endpoint.

Clarity would be enhanced in other respects, too. A socket is not identified by the combination of IP address and port:

[...]TCP demultiplexes incoming segments using all four values that comprise the local and foreign addresses: destination IP address, destination port number, source IP address, and source port number. TCP cannot determine which process gets an incoming segment by looking at the destination port only. Also, the only one of the [various] endpoints at [a given port number] that will receive incoming connection requests is the one in the listen state. (p255, TCP-IP Illustrated Volume 1, W. Richard Stevens)

As you can see, it is not just possible but quite likely for a network service to have numerous sockets with the same address/port, but only one listener socket on a particular address/port combination. Typical library implementations present a socket class, an instance of which is used to create and manage a connection. This is extremely unfortunate, since it causes confusion and has lead to widespread conflation of the two concepts.

Hagrawal doesn't believe me (see comments) so here's a real sample. I connected a web browser to http://dilbert.com and then ran netstat -an -p tcp. The last six lines of the output contain two examples of the fact that address and port are not enough to uniquely identify a socket. There are two distinct connections between 192.168.1.3 (my workstation) and 54.252.94.236:80 (the remote HTTP server)

  TCP    192.168.1.3:63240      54.252.94.236:80       SYN_SENT
  TCP    192.168.1.3:63241      54.252.94.236:80       SYN_SENT
  TCP    192.168.1.3:63242      207.38.110.62:80       SYN_SENT
  TCP    192.168.1.3:63243      207.38.110.62:80       SYN_SENT
  TCP    192.168.1.3:64161      65.54.225.168:443      ESTABLISHED

Since a socket is the endpoint of a connection, there are two sockets with the address/port combination 207.38.110.62:80 and two more with the address/port combination 54.252.94.236:80.

I think Hagrawal's misunderstanding arises from my very careful use of the word "identifies". I mean "completely, unambiguously and uniquely identifies". In the above sample there are two endpoints with the address/port combination 54.252.94.236:80. If all you have is address and port, you don't have enough information to tell these sockets apart. It's not enough information to identify a socket.

Addendum

Paragraph two of section 2.7 of RFC793 says

A connection is fully specified by the pair of sockets at the ends. A local socket may participate in many connections to different foreign sockets.

This definition of socket is not helpful from a programming perspective because it is not the same as a socket object, which is the endpoint of a particular connection. To a programmer, and most of this question's audience are programmers, this is a vital functional difference.

@plugwash makes a salient observation.

The fundamental problem is that the TCP RFC definition of socket is in conflict with the defintion of socket used by all major operating systems and libraries.

By definition the RFC is correct. When a library misuses terminology, this does not supersede the RFC. Instead, it imposes a burden of responsibility on users of that library to understand both interpretations and to be careful with words and context. Where RFCs do not agree, the most recent and most directly applicable RFC takes precedence.

References

  1. TCP-IP Illustrated Volume 1 The Protocols, W. Richard Stevens, 1994 Addison Wesley

  2. RFC793, Information Sciences Institute, University of Southern California for DARPA

  3. RFC147, The Definition of a Socket, Joel M. Winett, Lincoln Laboratory

Gaussmeter answered 30/9, 2008 at 10:4 Comment(42)
Perhaps, a real world analogy to keywords socket and port would help those who up-voted the question. Still a great explanation!Pyrone
@Pyrone - a real world analogy to ports has been present since very early drafts. Personally I think "socket" is an explanation in one word, but I have acted on your suggested and pointed this out in the article text.Gaussmeter
Peter: Can I say this: "A socket is an endpoint of a virtual connection between two processes defined by an IP address and a port number running on the network in UNIX."?Estrade
@Alex - I know you meant well, but it wouldn't be smart for me to edit your answers in French, there's too high a risk of my not understanding the subtleties. J'ai carrément dit que la « porte » se traduit par « door ». Le but était de souligner le fait que, même dans une autre langue, que le port de mot signifie point d'entrée ou la sortie, à souligner les similitudes ontologiques primordial. I have updated the text to prevent misinterpretation, thank you for bringing this to my attention.Gaussmeter
"An endpoint (socket) is defined by the combination of a network address and a port identifier. Note that address/port does not completely identify a socket (more on this later)." Is it defined as network address and a port identifier or not?Craggy
@Craggy - Read the whole answer. There is a difference between being defined by something and being identified by it. For example instances of a class are defined by the class. They are partly but not completely identified by it.Gaussmeter
@PeterWone I did read the whole answer, lol. I reread it just now and it makes sense. I didn't realize he was saying that the system needed more information to identify a socket than what it is defined as.Craggy
So basically is a socket a "combination of port and ip number" or not ? because he first says so and then says "A socket is not identified by the combination of IP address and port ". Someone please please explain.Azure
It's partly identified by IP and port. That's enough to create one. But you can create another one with the same IP and port so long as the other end is differentGaussmeter
I didn't voted because I disagree with this statement - "A socket is not identified by the combination of IP address and port:" .. Read TCP RFC - tools.ietf.org/html/rfc793 .. It is very clear that socket is combination of IP and port, if you know IP and port then you have identified a socket or endpoint, if you know pair of socket i.e. client IP+port and server IP+port then you have identified a unique connection ..Silhouette
As defined in the RFC763: Connections: The reliability and flow control mechanisms described above require that TCPs initialize and maintain certain status information for each data stream. The combination of this information, including sockets, sequence numbers, and window sizes, is called a connection. Each connection is uniquely specified by a pair of sockets identifying its two sides.Ellmyer
Check this #152957Uranology
"In the above sample there are two endpoints with the address/port combination 54.252.94.236:80. If all you have is address and port, you don't have enough information to tell these sockets apart. It's not enough information to identify a socket." Aren't those the same sockets, but different connections, between the two connections you have 3 sockets, 2 locals and one same server socket being connected to; or are they in fact two different sockets? There would be no telling them apart because they are the same, but to tell the connections apart you would need the different local sockets.Wiburg
@AndrewClavin - exactly: same address/port pair, different socket objects and different connections, the significance of which is that the address/port pair doesn't completely identify an endpoint. If this happened in a single app you wrote, your code would have two different object references.Gaussmeter
Different socket object; or same socket object, different socket object reference so two different socket object references to same external socket object?Wiburg
-1 Your answer is simply wrong. You: "A TCP socket is ... the endpoint of a specific connection." RFC 793: "a socket may be simultaneously used in multiple connections." I'm not sure what libraries you're using, but in libraries I've used, socket objects have been uniquely defined by an IP and port and have spawned connection objects for each remote socket.Adenoidectomy
@Adenoidectomy If your libraries use the same socket object in multiple connections, how do you know which connection you're using at any given moment? All you have is a socket object reference, and according to you it's the same object for all the connections sharing that logical endpoint.Gaussmeter
@Peter: As I said, you have multiple connection objects.Adenoidectomy
@PeterWone The summary here is good, and it's clear you understand the issues. The exposition, example, and this comment discussion are awkward and could be improved by clarifying the difference between establishing a connection and data transfer on an already established connection. I think that is the main point of contention/confusion here. A socket that is listening is identified uniquely by the IP & port number. Only an established connection needs a remote IP & port to demux.Quadrireme
A very nice answer. I have just started learning networking. I am confused with one more thing. An IP address defines a device. A port defines an application (no?) on that device. So why does that particular application needs even deeper level of identification with a socket? I mean why does two applications need multiple connections?Exo
@ReeshabhRanjan - A port does not define an application. For starters the term application is usually taken as meaning a complete executable object, and may offer more than one service. Even if you meant a service, while there is correspondence between WKPs (Well Known Ports) and services, eg 80 is well known as the http port, ports outside published WKPs are frequently dynamically allocated. You have a lot of reading ahead of you. There's lots of material on the web, but I still think you would do well to get a textbook like the one I mentioned.Gaussmeter
@ReeshabhRanjan - I know I haven't answered your question. It's too big for a comment response. If you post your own question referencing this one (if you don't do that they'll probably close it as a duplicate) and then asking your question above, I will try to find time for the length examination of the subject that it requires. Or I may simply write some material and do a powerpoint presentation on youtube.Gaussmeter
@PeterWone Thank you a lot for your help. Here is the question: stackoverflow.com/questions/47430923/why-a-socket-is-neededExo
The fundamental problem is that the TCP RFC definition of socket is in conflict with the defintion of socket used by all major operating systems and libraries.Colchis
Very good answer apart from the “socket is not identified by the IP and port”. You are confusing the socket objects( created using Java,C# etc) with the socket primitive provided by the operating system. At higher level of abstraction you may have many objects with same IP and port but at the OS level they map to the same socket. Thus you can identify a socket(OS primitive and not some object in xyz language) with IP and Port.Frodi
While I sense that there is much to appreciate in this answer it does not advance my understanding one bit. In other words my ability to code using sockets is not served by this response. It sacrifices comprehensibility for faithfulness. What would help is a working definition that the reader can use followed by a description that details how this fits into a bigger picture of the whole. A picture could also help.Dogma
@PeterWone Great answer. a) You mention "service" in various contexts. What do you mean? b) "ambiguity can be resolved using the routing table by selecting the interface with the shortest route to the remote endpoint" In your vision how would your imaginary networking library provide that to the developer and how would it (in short) implement it?Selfrespect
@Quadrireme - I've been thinking about your comment for some time. My answer could be clearer but the score suggests many people like it as is. These folk already have a working knowledge and appreciate examination of the subtleties. Those with an established incompatible mental model actively dislike it, and justify their prejudices with obsolete RFCs or out of scope things like object models. I'll never please everyone.Gaussmeter
It is a long answer, but still incomplete. <IP>:<Port> is the external representation of a socket, internally it's a special file one can read from and write to, afaik. The <IP>:<Port> basically tells the kernel to which sockets messages should be written to when they are received from a network card. In the same way you could also read and write to the socket with two processes communicating locally alone, and not necessarily using either TCP or IP protocols. Did I misunderstood that?Evadne
@erikbwork Please don't mixup socket and file descriptor. In Linux everything is a file or a process. Hence sockets are implemented as file descriptors but this is not necessary on other platforms.Jerkwater
Helpful answer! I think a lot of the confusion could be avoided by distinguishing between a socket address and socket in the context of a TCP connection. A socket address is the IP+port, whereas a socket represents one endpoint of a connection. A socket has a socket address, but a socket address isn't itself a socket.Bucaramanga
I understand the whole discussion but my question is who needs(or use) this socket(2 IP and 2 Port) when server and client needs only 1 IP and 1 Port to send the data to end point???@Peter Wone, @hagrawalPaleography
@stackdotpop: "A pair of sockets uniquely identifies each connection. That is, a socket may be simultaneously used in multiple connections." - from tools.ietf.org/html/rfc793 For data exchange, a connection is needed, and in a connection a pair of sockets come into play.Silhouette
@stackdotpop: I feel it is all about the usage of terminology when speaking strictly - read https://mcmap.net/q/46883/-what-39-s-the-difference-between-endpoint-and-socket... in general we tend to use terms/concepts interchangeably and other person with understand it because he/she knows the context, but when speaking strictly without any context then same thing can't be true...Silhouette
from the reference of RFC at 2.7 to define a connection fully 2 pair of socket are needed and this connection is called full duplex now it's clear thanks @hagrawalPaleography
There can only be one listener socket for a given address/port combination. Then what does setsockopt(SO_REUSEPORT) do?Crunch
@Crunch it's for use with UDP which doesn't do connections and therefore has utterly different semantics.Gaussmeter
This and most other explanations of sockets on the web don't mention that there is a second type of socket, a Unix domain or IPC socket.Socialist
@Socialist people who care about that already know.Gaussmeter
@Adenoidectomy Would you mind to tell me what library you've used? (You mentioned it at this comment : #152957)Yoo
I think problem is BSU-based socket is NOT fully implemented as TCP RFC said. According to RFC, a single socket should have been able to be connected to multiple remote sockets. But (maybe because of implementation issues), in BSD-style TCP world, there is no this kind of a shared socket concept, instead a TCP connection is mapped to only a single socket. So, in this world, a socket can NOT be identified by just one-side of IP/port. And because this BSD-style became dominant style nowadays, it made us to consider that a TCP socket is identified by four values, not by two values.Yoo
And, IMHO, it's very important to understand real implementation because it affects our understanding how it actually works.Yoo
V
217

A socket consists of three things:

  1. An IP address
  2. A transport protocol
  3. A port number

A port is a number between 1 and 65535 inclusive that signifies a logical gate in a device. Every connection between a client and server requires a unique socket.

For example:

  • 1030 is a port.
  • (10.1.1.2 , TCP , port 1030) is a socket.
Varro answered 2/8, 2012 at 17:10 Comment(13)
No. A socket consists of five things: {protocol, local address, local port, remote address, remote port}.Francis
@Varro - "An IP address... Atransport protocol..." if you called out an IP address, you already specified the transport protocol. Anyways, I've always seen them formally described as the 4-tuple {local address, local port, remote address, remote port} (similar to EJP's answer).Etruscan
How can the IP address read in Transport Layer? How does TCP decide which socket it will pass the message to? It must check the IP address obviously, but how? It is not contained in the TCP header, so how is it possible?Utilitarian
@KorayTugay It's in the IP header. What makes you think the TCP layer can't see that?Francis
@EJP as I can see in the most voted answer above that a socket is NOT the connection itself but it is the end point of a connection then how come it can include both local and remote ports and ip addresses. A socket will represent only one side of the connection i.e. either local port and local ip address OR remote port and remote ip accress. Kindly correct me if I'm wrong.Vorous
@Vorous The connection is defined by the tuple, and so therefore are the sockets that form its endpoints. See RFC 793.Francis
@EJB A socket is just identifiable by IP:Port, not a 5-elements tuple. RFC 793: To allow for many processes within a single Host to use TCP communication facilities simultaneously, the TCP provides a set of addresses or ports within each host. Concatenated with the network and host addresses from the internet communication layer, this forms a socket.Romeliaromelle
@Gab是好人 Your quotation doesn't agree with you, and it does agree exactly with what I said. The socket is identified by the 5-tuple, which consist of the protocol and the two addresses, which in turn each consist of the IP address and port. You missed the fact that 'addresses' is plural in what you quoted.Francis
@EJP Still RFC 793 : "A pair of sockets uniquely identifies each connection. That is, a socket may be simultaneously used in multiple connections." If a socket already consisted of five things, how could there be" a pair of sockets" in my citation?Romeliaromelle
@Gab是好人 I cannot follow your non sequitur. The fact remains that a TCP socket is identified by a 5-tuple. Otherwise it couldn't know who it was connected to; it couldn't know its local IP:port; getpeername() and getsockname() couldn't work; ...Francis
A socket is combination of 4 things.Hippocrene
@praveenjain Five, and I have listed them above. Which one do you want to remove?Francis
A socket does not need an IP address not a port number. Neither Unix domain socket nor socketCan sockets need them. Only network sockets such as TCP sockets need them.Finsteraarhorn
B
127

A socket represents a single connection between two network applications. These two applications nominally run on different computers, but sockets can also be used for interprocess communication on a single computer. Applications can create multiple sockets for communicating with each other. Sockets are bi-directional, meaning that either side of the connection is capable of both sending and receiving data. Therefore a socket can be created theoretically at any level of the OSI model from 2 upwards. Programmers often use sockets in network programming, albeit indirectly. Programming libraries like Winsock hide many of the low-level details of socket programming. Sockets have been in widespread use since the early 1980s.

A port represents an endpoint or "channel" for network communications. Port numbers allow different applications on the same computer to utilize network resources without interfering with each other. Port numbers most commonly appear in network programming, particularly socket programming. Sometimes, though, port numbers are made visible to the casual user. For example, some Web sites a person visits on the Internet use a URL like the following:

http://www.mairie-metz.fr:8080/ In this example, the number 8080 refers to the port number used by the Web browser to connect to the Web server. Normally, a Web site uses port number 80 and this number need not be included with the URL (although it can be).

In IP networking, port numbers can theoretically range from 0 to 65535. Most popular network applications, though, use port numbers at the low end of the range (such as 80 for HTTP).

Note: The term port also refers to several other aspects of network technology. A port can refer to a physical connection point for peripheral devices such as serial, parallel, and USB ports. The term port also refers to certain Ethernet connection points, such as those on a hub, switch, or router.

ref http://compnetworking.about.com/od/basicnetworkingconcepts/l/bldef_port.htm

ref http://compnetworking.about.com/od/itinformationtechnology/l/bldef_socket.htm

Boyett answered 30/9, 2008 at 10:7 Comment(3)
Layer 2 on the OSI model is a connection between nodes, it has no mechanism of connecting processes. I don't believe you can consider a socket existing at OSI l2.Aldosterone
A circuit is a connection - a socket is an endpoint. A connection consists of 2 sockets.Chalk
"A socket represents a single connection between two network applications." That does not match RFC 793, Transmission Control Protocol that explains: "To allow for many processes within a single Host to use TCP communication facilities simultaneously, the TCP provides a set of addresses or ports within each host. Concatenated with the network and host addresses from the internet communication layer, this forms a socket. A pair of sockets uniquely identifies each connection."Wert
W
117

With some analogy

Although a lot technical stuff is already given above for sockets... I would like to add my answer, just in case , if somebody still could not feel the difference between ip, port and sockets

Consider a server S,

and say person X,Y,Z need a service (say chat service) from that server S

then

IP address tells --> who? is that chat server 'S' that X,Y,Z want to contact

okay, you got "who is the server"

but suppose that server 'S' is providing some other services to other people as well,say 'S' provides storage services to person A,B,C

then

port tells ---> which? service you (X,Y,Z) need i.e. chat service and not that storage service

okay.., you make server to come to know that 'chat service' is what you want and not the storage

but

you are three and the server might want to identify all the three differently

there comes the socket

now socket tells--> which one? particular connection

that is , say ,

socket 1 for person X

socket 2 for person Y

and socket 3 for person Z

Wyatan answered 20/6, 2016 at 9:57 Comment(1)
So X,Y,Z would connect to the same port, i.e. same service, but have different sockets on the server side? So when, say, X sends some packet to the server, it's going to say: 'find me the (protocol, X's IP, X's port, S's IP, S's port) socket' and send to the chat app. I assume there must be a binding between some application -specific objects and socket objects? For example, when i get some data from socket-1, i want to display that as a user message, but the app needs to know messages from socket A are from User-X.Korean
K
50

Firsty, I think we should start with a little understanding of what constitutes getting a packet from A to B.

A common definition for a network is the use of the OSI Model which separates a network out into a number of layers according to purpose. There are a few important ones, which we'll cover here:

  • The data link layer. This layer is responsible for getting packets of data from one network device to another and is just above the layer that actually does the transmitting. It talks about MAC addresses and knows how to find hosts based on their MAC (hardware) address, but nothing more.
  • The network layer is the layer that allows you to transport data across machines and over physical boundaries, such as physical devices. The network layer must essentially support an additional address based mechanism which relates somehow to the physical address; enter the Internet Protocol (IPv4). An IP address can get your packet from A to B over the internet, but knows nothing about how to traverse individual hops. This is handled by the layer above in accordance with routing information.
  • The transport layer. This layer is responsible for defining the way information gets from A to B and any restrictions, checks or errors on that behaviour. For example, TCP adds additional information to a packet such that it is possible to deduce if packets have been lost.

TCP contains, amongst other things, the concept of ports. These are effectively different data endpoints on the same IP address to which an Internet Socket (AF_INET) can bind.

As it happens, so too does UDP, and other transport layer protocols. They don't technically need to feature ports, but these ports do provide a way for multiple applications in the layers above to use the same computer to receive (and indeed make) outgoing connections.

Which brings us to the anatomy of a TCP or UDP connection. Each features a source port and address, and a target port and address. This is so that in any given session, the target application can respond, as well as receive, from the source.

So ports are essentially a specification-mandated way of allowing multiple concurrent connections sharing the same address.

Now, we need to take a look at how you communicate from an application point of view to the outside world. To do this, you need to kindly ask your operating system and since most OSes support the Berkeley Sockets way of doing things, we see we can create sockets involving ports from an application like this:

int fd = socket(AF_INET, SOCK_STREAM, 0); // tcp socket
int fd = socket(AF_INET, SOCK_DGRAM, 0); // udp socket
// later we bind...

Great! So in the sockaddr structures, we'll specify our port and bam! Job done! Well, almost, except:

int fd = socket(AF_UNIX, SOCK_STREAM, 0);

is also possible. Urgh, that's thrown a spanner in the works!

Ok, well actually it hasn't. All we need to do is come up with some appropriate definitions:

  • An internet socket is the combination of an IP address, a protocol and its associated port number on which a service may provide data. So tcp port 80, stackoverflow.com is an internet socket.
  • An unix socket is an IPC endpoint represented in the file system, e.g. /var/run/database.sock.
  • A socket API is a method of requesting an application be able to read and write data to a socket.

Voila! That tidies things up. So in our scheme then,

  • A port is a numeric identifier which, as part of a transport layer protocol, identifies the service number which should respond to the given request.

So really a port is a subset of the requirements for forming an internet socket. Unfortunately, it just so happens that the meaning of the word socket has been applied to several different ideas. So I heartily advise you name your next project socket, just to add to the confusion ;)

Klong answered 7/4, 2012 at 20:17 Comment(2)
This is why bullets don't leave and won't leave Powerpoint; they work!Regin
Very nice introduction to tcp-ip and network communication. Beginners, read this first.Beneficiary
C
43

A socket = IP Address + a port (numeric address)
Together they identify an end-point for a network connection on a machine. (Did I just flunk network 101?)

Cassaba answered 30/9, 2008 at 10:5 Comment(3)
I believe port has broader meaning than your definition.Unpopular
And sockets are not only subject to the TCP/IP stack. See UNIX domain sockets or inter process communication sockets in general.Mariel
not sure about this answer. You can use HTTP to communicate with another process via sockets without assigning a port.Blennioid
A
43

Generally, you will get a lot of theoretical but one of the easiest ways to differentiate these two concepts is as follows:

In order to get a service, you need a service number. This service number is called a port. Simple as that.

For example, the HTTP as a service is running on port 80.

Now, many people can request the service, and a connection from client-server gets established. There will be a lot of connections. Each connection represents a client. In order to maintain each connection, the server creates a socket per connection to maintain its client.

Aether answered 13/12, 2013 at 10:9 Comment(9)
Does each socket require it's own port?Gaye
Awesome. The most simple way to present a mountain-knowledge.Estrellaestrellita
I am not sure if your statement: "the server creates socket per connection to maintain it's client" is correct.Pestiferous
@RushiAgrawal Then I suggest you look it up. Specifically, see man accept.Francis
This implies that for each socket which the server creates per connection to maintain its client can have the same port number (such as port 80 for HTTP connections continuation) but with different IP address of the clients which the requests for connections are sent from. right?Condottiere
The server creates a socket instance per connection. The problem here is the English language which is ambiguous with classes and instances.Gaussmeter
@KasunRandika That is correct. You are confusing sockets and ports.Francis
#11129712 states "All established client connections on that server are associated with that same listening port on the server side of the connection", which kind of contradicts "server creates a socket per connection to maintain its client".Stilton
@BenButterworth No it doesn't. You are conflating sockets and ports.Francis
L
37

These are basic networking concepts so I will explain them in an easy yet a comprehensive way to understand in details.

  • A socket is like a telephone (i.e. end to end device for communication)
  • IP is like your telephone number (i.e. address for your socket)
  • Port is like the person you want to talk to (i.e. the service you want to order from that address)
  • A socket can be a client or a server socket (i.e. in a company the telephone of the customer support is a server but a telephone in your home is mostly a client)

So a socket in networking is a virtual communication device bound to a pair (ip , port) = (address , service).

Note:

  • A machine, a computer, a host, a mobile, or a PC can have multiple addresses , multiple open ports, and thus multiple sockets. Like in an office you can have multiple telephones with multiple telephone numbers and multiple people to talk to.
  • Existence of an open/active port necessitate that you must have a socket bound to it, because it is the socket that makes the port accessible. However, you may have unused ports for the time being.
  • Also note, in a server socket you can bind it to (a port, a specific address of a machine) or to (a port, all addresses of a machine) as in the telephone you may connect many telephone lines (telephone numbers) to a telephone or one specific telephone line to a telephone and still you can reach a person through all these telephone lines or through a specific telephone line.
  • You can not associate (bind) a socket with two ports as in the telephone usually you can not always have two people using the same telephone at the same time .
  • Advanced: on the same machine you cannot have two sockets with same type (client, or server) and same port and ip. However, if you are a client you can open two connections, with two sockets, to a server because the local port in each of these client's sockets is different)

Hope it clears you doubts

Leto answered 19/2, 2019 at 7:17 Comment(2)
It is interesting to see all these understandings and analogies of sockets/ports/ip addresses under this question. And I like this answer.Eleanore
Wow! What a good explanation and examples. +1 for this.Woolson
C
34

There seems to be a lot of answers equating socket with the connection between 2 PC's..which I think is absolutely incorrect. A socket has always been the endpoint on 1 PC, that may or may not be connected - surely we've all used listener or UDP sockets* at some point. The important part is that it's addressable and active. Sending a message to 1.1.1.1:1234 is not likely to work, as there is no socket defined for that endpoint.

Sockets are protocol specific - so the implementation of uniqueness that both TCP/IP and UDP/IP uses* (ipaddress:port), is different than eg., IPX (Network, Node, and...ahem, socket - but a different socket than is meant by the general "socket" term. IPX socket numbers are equivalent to IP ports). But, they all offer a unique addressable endpoint.

Since IP has become the dominant protocol, a port (in networking terms) has become synonomous with either a UDP or TCP port number - which is a portion of the socket address.

  • UDP is connection-less - meaning no virtual circuit between the 2 endpoints is ever created. However, we still refer to UDP sockets as the endpoint. The API functions make it clear that both are just different type of sockets - SOCK_DGRAM is UDP (just sending a message) and SOCK_STREAM is TCP (creating a virtual circuit).

  • Technically, the IP header holds the IP Address, and the protocol on top of IP (UDP or TCP) holds the port number. This makes it possible to have other protocols (eg. ICMP that have no port numbers, but do have IP addressing information).

Chalk answered 30/9, 2008 at 13:26 Comment(1)
Good answer for socket. Port indeed refers to TCP or UDP, which, I want to stress, not necessarily is used on top of IP.Doe
Z
30

Short brief answer.

A port can be described as an internal address within a host that identifies a program or process.

A socket can be described as a programming interface allowing a program to communicate with other programs or processes, on the internet, or locally.

Zrike answered 19/3, 2014 at 1:31 Comment(3)
The word 'internal' in the port description sounds rather like 'non-public' to me.Crosson
So Could we say :Sockets runs inside Ports ? or Ports runs inside Sockets ?Wrathful
@GuchoCa We can't say that either sockets or ports run at all, let alone one inside the other. Unclear what you're asking.Francis
C
23

They are terms from two different domains: 'port' is a concept from TCP/IP networking, 'socket' is an API (programming) thing. A 'socket' is made (in code) by taking a port and a hostname or network adapter and combining them into a data structure that you can use to send or receive data.

Corroboree answered 30/9, 2008 at 10:8 Comment(1)
For the most general answer, strike "made by taking a port and a hostname or network adapter and combining them into a." For example, a UNIX socket is (in code) a data structure (or object) that you can use to send or receive data.Noble
B
17

After reading the excellent up-voted answers, I found that the following point needed emphasis for me, a newcomer to network programming:

TCP-IP connections are bi-directional pathways connecting one address:port combination with another address:port combination. Therefore, whenever you open a connection from your local machine to a port on a remote server (say www.google.com:80), you are also associating a new port number on your machine with the connection, to allow the server to send things back to you, (e.g. 127.0.0.1:65234). It can be helpful to use netstat to look at your machine's connections:

> netstat -nWp tcp (on OS X)
Active Internet connections
Proto Recv-Q Send-Q  Local Address          Foreign Address        (state)    
tcp4       0      0  192.168.0.6.49871      17.172.232.57.5223     ESTABLISHED
...
Beneficiary answered 14/3, 2013 at 19:57 Comment(0)
G
14

A socket is a communication endpoint. A socket is not directly related to the TCP/IP protocol family, it can be used with any protocol your system supports. The C socket API expects you to first get a blank socket object from the system that you can then either bind to a local socket address (to directly retrieve incoming traffic for connection-less protocols or to accept incoming connection requests for connection-oriented protocols) or that you can connect to a remote socket address (for either kind of protocol). You can even do both if you want to control both, the local socket address a socket is bound to and the remote socket address a socket is connected to. For connection-less protocols connecting a socket is even optional but if you don't do that, you'll have to also pass the destination address with every packet you want to send over the socket as how else would the socket know where to send this data to? Advantage is that you can use a single socket to send packets to different socket addresses. Once you have your socket configured and maybe even connected, consider it to be a bi-directional communication pipe. You can use it to pass data to some destination and some destination can use it to pass data back to you. What you write to a socket is send out and what has been received is available for reading.

Ports on the other hand are something that only certain protocols of the TCP/IP protocol stack have. TCP and UDP packets have ports. A port is just a simple number. The combination of source port and destination port identify a communication channel between two hosts. E.g. you may have a server that shall be both, a simple HTTP server and a simple FTP server. If now a packet arrives for the address of that server, how would it know if that is a packet for the HTTP or the FTP server? Well, it will know so as the HTTP server will run on port 80 and the FTP server on port 21, so if the packet arrives with a destination port 80, it is for the HTTP server and not for the FTP server. Also the packet has a source port since without such a source port, a server could only have one connection to one IP address at a time. The source port makes it possible for a server to distinguish otherwise identical connections: they all have the same destination port, e.g. port 80, the same destination IP (the IP of the server), and the same source IP, as they all come from the same client, but as they have different source ports, the server can distinguish them from each other. And when the server sends back replies, it will do so to the port the request came from, that way the client can also distinguish different replies it receives from the same server.

Gilgamesh answered 30/9, 2008 at 10:24 Comment(5)
This is incorrect. A socket is not an endpoint. A socket is defined by two endpoints. Each endpoint is defined by a network address and a port. The purpose of ports is to differentiate multiple endpoints on the same network address, so that multiple concurrent sockets can be supported.Gaussmeter
I notice that RFC793 (original TCP spec) does refer to the combination of a network address and a port as a socket, so I can see where you got this, but it's still incorrect inasmuchas a socket is necessarily defined by two endpoints.Gaussmeter
On reflection the literature is contradictory and I apologise. Very strictly speaking communication does not occur until a TCP connection is established between two endpoints (aka sockets) each of which is identified by a network address and a port. I give up.Gaussmeter
@PeterWone I believe you can't define a socket by two endpoints: what about a server socket waiting for an incoming connection? It is alone, and still it's a socket. And you can't even define a socket related to network.. you may have sockets over files. Yes, network address + port is a socket, but I intend a socket as a superset.Doe
@Doe yes in this comment I have used the term socket incorrectly, and so have you, as your own example of a listening socket demonstrates. My own answer above discusses at length and with references the correct nomenclature and exactly what it means. What we have here in the comments on this question called a socket is a connection defined by two endpoints, each of which is a socket.Gaussmeter
A
13

A socket is a special type of file handle which is used by a process to request network services from the operating system. A socket address is the triple: {protocol, local-address, local-process} where the local process is identified by a port number.

In the TCP/IP suite, for example:

{tcp, 193.44.234.3, 12345}

A conversation is the communication link between two processes thus depicting an association between two. An association is the 5-tuple that completely specifies the two processes that comprise a connection: {protocol, local-address, local-process, foreign-address, foreign-process}

In the TCP/IP suite, for example:

{tcp, 193.44.234.3, 1500, 193.44.234.5, 21}

could be a valid association.

A half-association is either: {protocol, local-address, local-process}

or

{protocol, foreign-address, foreign-process}

which specify each half of a connection.

The half-association is also called a socket or a transport address. That is, a socket is an end point for communication that can be named and addressed in a network. The socket interface is one of several application programming interfaces (APIs) to the communication protocols. Designed to be a generic communication programming interface, it was first introduced by the 4.2BSD UNIX system. Although it has not been standardized, it has become a de facto industry standard.

Alphanumeric answered 9/6, 2014 at 12:18 Comment(4)
This answer is the one that did it for me. I guess it is because no one else mentioned the word association. Good explanation.Craggy
There is no process number in any of your examples. The word you are looking for is 'port'.Francis
Read the first para.. It's mentioned clearly there. Let me know of any ambiguity by quoting the exact phrase.. Would be helpful for me to improvise.Alphanumeric
I read it. The correct formulation would be "A socket address is the triple: {protocol, local-address, local-port-number]". A process can own multiple ports, which makes your formulation invalid.Francis
A
13

A socket address is an IP address & port number

123.132.213.231         # IP address
               :1234    # port number
123.132.213.231:1234    # socket address

A connection occurs when 2 sockets are bound together.

Adenoidectomy answered 24/1, 2017 at 17:4 Comment(2)
There is no such thing as binding two sockets together. The word 'bound' means something else with ports.Francis
This is wrong, a socket does not need an IP address nor a port number, only some network sockets need them. Neither do Unix domain sockets nor socketCAN sockets need them.Finsteraarhorn
A
11

An application consists of pair of processes which communicate over the network (client-server pair). These processes send and receive messages, into and from the network through a software interface called socket. Considering the analogy presented in the book "Computer Networking: Top Down Approach". There is a house that wants to communicate with other house. Here, house is analogous to a process, and door to a socket. Sending process assumes that there is a infrastructure on the other side of the door that will transport the data to the destination. Once the message is arrived on the other side, it passes through receiver's door (socket) into the house (process). This illustration from the same book can help you:
enter image description here
Sockets are part of transport layer, which provides logical communication to applications. This means that from application's point of view both hosts are directly connected to each other, even though there are numerous routers and/or switches between them. Thus a socket is not a connection itself, it's the end point of the connection. Transport layer protocols are implemented only on hosts, and not on intermediate routers.
Ports provide means of internal addressing to a machine. The primary purpose it to allow multiple processes to send and receive data over the network without interfering with other processes (their data). All sockets are provided with a port number. When a segment arrives to a host, the transport layer examines the destination port number of the segment. It then forwards the segment to the corresponding socket. This job of delivering the data in a transport layer segment to the correct socket is called de-multiplexing. The segment's data is then forwarded to the process attached to the socket.

Aliped answered 4/10, 2016 at 8:14 Comment(0)
U
9

The port was the easiest part, it is just a unique identifier for a socket. A socket is something processes can use to establish connections and to communicate with each other. Tall Jeff had a great telephone analogy which was not perfect, so I decided to fix it:

  • ip and port ~ phone number
  • socket ~ phone device
  • connection ~ phone call
  • establishing connection ~ calling a number
  • processes, remote applications ~ people
  • messages ~ speech
Undetermined answered 11/10, 2015 at 22:57 Comment(2)
Good clarification (especially when you consider the telephone switching history that's part of the foundation of networking terminology..)Pashto
Have a look at a netstat display some time. All sockets accepted from a listening socket share the same port. Ergo a port is not a unique identifier for a socket.Francis
H
7

A socket is a structure in your software. It's more-or-less a file; it has operations like read and write. It isn't a physical thing; it's a way for your software to refer to physical things.

A port is a device-like thing. Each host has one or more networks (those are physical); a host has an address on each network. Each address can have thousands of ports.

One socket only may be using a port at an address. The socket allocates the port approximately like allocating a device for file system I/O. Once the port is allocated, no other socket can connect to that port. The port will be freed when the socket is closed.

Take a look at TCP/IP Terminology.

Hire answered 30/9, 2008 at 10:9 Comment(12)
This description of socket is pretty off base. A socket is about the connection between a pair of tuples where a tuple refers to an IP ADDR & Port pair. Additionally many sockets CAN connect to the same port. How do you think a web server takes multiple connections on port 80? This is a poor answerSepsis
Sorry. Multiple sockets are not connected to port 80. One socket is connected and spawns additional sockets where the real transfer happens. See opengroup.org/onlinepubs/009695399/functions/listen.html.Hire
Actually, the description at opengroup.org/onlinepubs/009695399/functions/connect.html is better. The peer socket returned by a connection is NOT on port 80.Hire
This post is incorrect in several particulars and misleading in several respects.Gaussmeter
@Woolson Wone: Which particulars? Which aspects? Hoping to learn from my mistakes.Hire
"Once the port is allocated, no other socket can connect to that port." Do you mean to add that once a socket is "destroyed" the port is freed?Cowling
Apologies for length of delay. I'm totally with you on the details in negative feedback thing, so here goes: a socket is not a structure in software, it is the abstraction of an endpoint - not even an abstraction of a connection. You go on to say that the socket is more or less a file, further conflating socket with connection and additionally conflating it with a completely separate abstraction (the stream) which though a very typical approach to communication in C like languages has in and of itself nothing to do with connections or sockets.Gaussmeter
I want to downvote the downvoters and send them back to networking 101.Chloroplast
Multiple sockets are connected to port 80, as the merest glance at a netstat display will confirm. There is nothing in either of your citations that says otherwise. @Chloroplast I suggest you refresh it yourself.Francis
127.0.0.1:80 != 127.0.0.2:80Chloroplast
@Chloroplast I fail to se the relevance of that comment. Have a look at a netstat display on an active HTTP server. You will typically see many lines with both 0.0.0.0:80 and ESTABLISHED. See for example here.Francis
@Hire The The socket returned by a connection to port 80 is indeed on port 80. See any netstat display. It has a different local port, but the remote port is port 80. And at the server, the local port of any accepted socket is the same as that of the listening socket it was accepted from.Francis
L
7

from Oracle Java Tutorial:

A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to.

Lindi answered 12/4, 2014 at 14:3 Comment(3)
That's only a tutorial, and certainly not a normative reference.Francis
"A socket is one endpoint of a two-way communication link" Is that not a socket definition, Not a java tutorial??Spongioblast
@prayagupd Of course it's a definition, but it's from a tutorial, not a specification.Francis
D
7

Port and socket can be compared to the Bank Branch.

The building number of the "Bank" is analogous to IP address. A bank has got different sections like:

  1. Savings account department
  2. Personal loan department
  3. Home loan department
  4. Grievance department

So 1 (savings account department), 2 (personal loan department), 3 (home loan department) and 4 (grievance department) are ports.

Now let us say you go to open a savings account, you go to the bank (IP address), then you go to "savings account department" (port number 1), then you meet one of the employees working under "savings account department". Let us call him SAVINGACCOUNT_EMPLOYEE1 for opening account.

SAVINGACCOUNT_EMPLOYEE1 is your socket descriptor, so there may be SAVINGACCOUNT_EMPLOYEE1 to SAVINGACCOUNT_EMPLOYEEN. These are all socket descriptors.

Likewise, other departments will be having employess working under them and they are analogous to socket.

Dmitri answered 11/4, 2017 at 12:21 Comment(0)
A
5

A socket is a data I/O mechanism. A port is a contractual concept of a communication protocol. A socket can exist without a port. A port can exist witout a specific socket (e.g. if several sockets are active on the same port, which may be allowed for some protocols).

A port is used to determine which socket the receiver should route the packet to, with many protocols, but it is not always required and the receiving socket selection can be done by other means - a port is entirely a tool used by the protocol handler in the network subsystem. e.g. if a protocol does not use a port, packets can go to all listening sockets or any socket.

Absquatulate answered 30/9, 2008 at 10:8 Comment(0)
B
5

Port:

A port can refer to a physical connection point for peripheral devices such as serial, parallel, and USB ports. The term port also refers to certain Ethernet connection points, s uch as those on a hub, switch, or router.

Socket:

A socket represents a single connection between two network applications. These two applications nominally run on different computers, but sockets can also be used for interprocess communication on a single computer. Applications can create multiple sockets for communicating with each other. Sockets are bidirectional, meaning that either side of the connection is capable of both sending and receiving data.

Basra answered 30/9, 2008 at 10:23 Comment(3)
A TCP or UDP port does not refer to anything physical, or to Ethernet connection points either. You haven't answered the question.Francis
@Francis I don't reed anything about TCP nor UDP in the question.Finsteraarhorn
What you don't need is anything about 'physical connection point'. This is not correct. A port is a logical entity that doesn't refer to anything physical at all.Francis
S
5

Relative TCP/IP terminology which is what I assume is implied by the question. In layman's terms:

A PORT is like the telephone number of a particular house in a particular zip code. The ZIP code of the town could be thought of as the IP address of the town and all the houses in that town.

A SOCKET on the other hand is more like an established phone call between telephones of a pair of houses talking to each other. Those calls can be established between houses in the same town or two houses in different towns. It's that temporary established pathway between the pair of phones talking to each other that is the SOCKET.

Sepsis answered 30/9, 2008 at 12:12 Comment(1)
A socket is an endpoint. It exists before a connection is established (TCP), or in the absence of a connection (UDP). Ergo it is not itself the connection.Francis
D
4

In a broad sense, Socket - is just that, a socket, just like your electrical, cable or telephone socket. A point where "requisite stuff" (power, signal, information) can go out and come in from. It hides a lot of detailed stuff, which is not required for the use of the "requisite stuff". In software parlance, it provides a generic way of defining a mechanism of communication between two entities (those entities could be anything - two applications, two physically separate devices, User & Kernel space within an OS, etc)

A Port is an endpoint discriminator. It differentiates one endpoint from another. At networking level, it differentiates one application from another, so that the networking stack can pass on information to the appropriate application.

Depolarize answered 31/12, 2008 at 7:47 Comment(0)
A
4

Socket is an abstraction provided by kernel to user applications for data I/O. A socket type is defined by the protocol it's handling, an IPC communication etc. So if somebody creates a TCP socket he can do manipulations like reading data to socket and writing data to it by simple methods and the lower level protocol handling like TCP conversions and forwarding packets to lower level network protocols is done by the particular socket implementation in the kernel. The advantage is that user need not worry about handling protocol specific nitigrities and should just read and write data to socket like a normal buffer. Same is true in case of IPC, user just reads and writes data to socket and kernel handles all lower level details based on the type of socket created.

Port together with IP is like providing an address to the socket, though its not necessary, but it helps in network communications.

Argumentation answered 16/10, 2013 at 10:8 Comment(0)
G
3

A port denotes a communication endpoint in the TCP and UDP transports for the IP network protocol. A socket is a software abstraction for a communication endpoint commonly used in implementations of these protocols (socket API). An alternative implementation is the XTI/TLI API.

See also:

Stevens, W. R. 1998, UNIX Network Programming: Networking APIs: Sockets and XTI; Volume 1, Prentice Hall.
Stevens, W. R., 1994, TCP/IP Illustrated, Volume 1: The Protocols, Addison-Wesley.

Godson answered 30/9, 2008 at 10:28 Comment(0)
F
3

Socket is SW abstraction of networking endpoint, used as the interface to the application. In Java, C# it is represented by object, in Linux, Unix it is a file.

Port is just a property of a socket you have specify if you want to establish a communication. To receieve packet from a socket you have to bind it to specific local port and NIC (with local IP address) or all NICs (INADDR_ANY is specified in the bind call). To send packet, you have to specify port and IP of the remote socket.

Flaunt answered 22/10, 2018 at 14:59 Comment(0)
C
2

A socket is basically an endpoint for network communication, consisting of at least an IP-address and a port. In Java/C# a socket is a higher level implementation of one side of a two-way connection.

Also, a (non-normative) definition in the Java Tutorial.

Coloration answered 30/9, 2008 at 10:8 Comment(0)
C
2

Already theoretical answers have been given to this question. I would like to give a practical example to this question, which will clear your understanding about Socket and Port.

I found it here

This example will walk you thru the process of connecting to a website, such as Wiley. You would open your web browser (like Mozilla Firefox) and type www.wiley.com into the address bar. Your web browser uses a Domain Name System (DNS) server to look up the name www.wiley.com to identify its IP address is. For this example, the address is 192.0.2.100.

Firefox makes a connection to the 192.0.2.100 address and to the port where the application layer web server is operating. Firefox knows what port to expect because it is a well-known port . The well-known port for a web server is TCP port 80.

The destination socket that Firefox attempts to connect is written as socket:port, or in this example, 192.0.2.100:80. This is the server side of the connect, but the server needs to know where to send the web page you want to view in Mozilla Firefox, so you have a socket for the client side of the connection also.

The client side connection is made up of your IP address, such as 192.168.1.25, and a randomly chosen dynamic port number. The socket associated with Firefox looks like 192.168.1.25:49175. Because web servers operate on TCP port 80, both of these sockets are TCP sockets, whereas if you were connecting to a server operating on a UDP port, both the server and client sockets would be UDP sockets.

Crossbeam answered 26/6, 2013 at 12:57 Comment(1)
Very poor quality citation. The third paragraph misuses the word 'socket' as though it meant 'IP address'. It doesn't.Francis
P
2

A single port can have one or more sockets connected with different external IP's like a multiple electrical outlet.

  TCP    192.168.100.2:9001     155.94.246.179:39255   ESTABLISHED     1312
  TCP    192.168.100.2:9001     171.25.193.9:61832     ESTABLISHED     1312
  TCP    192.168.100.2:9001     178.62.199.226:37912   ESTABLISHED     1312
  TCP    192.168.100.2:9001     188.193.64.150:40900   ESTABLISHED     1312
  TCP    192.168.100.2:9001     198.23.194.149:43970   ESTABLISHED     1312
  TCP    192.168.100.2:9001     198.49.73.11:38842     ESTABLISHED     1312
Primary answered 31/8, 2015 at 3:43 Comment(0)
D
2

Uff.. too many people linking socket concept to a two-endpoints communication, mostly on TCP/IP protocol. But:

  • NO - Socket is not related to a two-endpoint communication. It's the local endpoint, which can or cannot be connected on the other side (Think about a server socket listening for incoming connection)
  • NO - Socket it's not strictly related to TCP/IP. It is defined with a protcol, which can be TCP/IP, but can be anything else. For example you can have socket that communicates over files. You can also implement a new protocol yourself to have a communication over USB lamp which sends data by flashing: that would still be a socket from the application point of view.

Regarding the port concept it's correct what you read on other answers. Port is mostly intended to be the number value (2 bytes, 0-65535) in TCP or UDP packet. Just let me stress that TCP or UPD not necessarily are used on top of IP. So:

  • NO - it's not correct saying that port is part of TCP/IP or UDP/IP. It's part of TCP or UDP, or any other protocol which define and use it. IP has no knowledge of what a port is.
Doe answered 17/6, 2021 at 9:13 Comment(0)
S
1

I know that there are lot of explanations. But, there is one more easy way to understand with practical example. We all can connect to HTTP port 80, but does it mean only one user can connect to that port at a time?. The answer is obviously 'no'. Multiple users for multiple purposes can access HTTP port 80 but they still get proper response they are waiting for, from the server, can't they?. Now think about it for a minute, how?. Yes you are correct, its IP address that uniquely identifies different users who contacts for different purposes. If you would have read the previous answers before reaching here, you would know that IP address is a part of information that socket consists. Think about it, is it possible to have a communication without sockets?. The answer is 'Yes' but you cannot run more than one application in a port but we know that we are not a 'Dump' switch that runs on just hardware.

Stringpiece answered 21/8, 2016 at 17:33 Comment(3)
No it isn't. It is the 5-tuple {protocol, source IP,source port, target IP, target port}.Francis
Yes, I agree. we are adding intelligence as switches evolve.Stringpiece
That's not what I said, and it is not what you claim to be agreeing with. Switches have nothing to do with it.Francis
R
0

A port number is a way to identify a specific process to which an internet or other network message is to be forwarded when it arrives at a server.

Any program when in the state of execution is called a process and the port number is used to identify a specific process within a certain system. Imagine you send a letter one of the house members, address of this house is IP address and the person that you want the letter to be delivered is a port number.

  • Socket is one endpoint of a two way communication link between two processes on the network. A socket consists of a port number and an IP. TCP uses this information to identify the process on a specific IP address to which that data needs to be delivered. If you set up a socket connection between 2 in local host, their ip address will be same because they are on the same machine, or as I mentioned above example they are in the same house. But their port number will be different. Because they are two different people in the same house, server and client.
Rueful answered 21/2, 2023 at 22:3 Comment(0)
F
-1

A port is an entity that is used by networking protocols to attain access to connected hosts. Ports could be application-specific or related to a certain communication medium. Different protocols use different ports to access the hosts, like HTTP uses port 80 or FTP uses port 23. You can assign user-defined port numbers in your application, but they should be above 1023.

Ports open up the connection to the required host while sockets are an endpoint in an inter-network or an inter-process communication. Sockets are assigned by APIs(Application Programming Interface) by the system.

A more subtle difference can be made saying that, when a system is rebooted ports will be present while the sockets will be destroyed.

Freeboard answered 18/3, 2013 at 14:56 Comment(1)
No they won't. Ports will only be present when a process opens one for TCP listening or UDP send/receive.Francis
D
-1

As simply as possible, there's no physical difference between a socket and a port, the way there is between, e.g., PATA and SATA. They're just bits of software reading and writing a NIC.

A port is essentially a public socket, some of which are well-known/well-accepted, the usual example being 80, dedicated to HTTP. Anyone who wants to exchange traffic using a certain protocol, HTTP in this instance, canonically goes to port 80. Of course, 80 is not physically dedicated to HTTP (it's not physically anything, it's just a number, a logical value), and could be used on some particular machine for some other protocol ad libitum, as long as those attempting to connect know which protocol (which could be quite private) to use.

A socket is essentially a private port, established for particular purposes known to the connecting parties but not necessarily known to anyone else. The underlying transport layer is usually TCP or UDP, but it doesn't have to be. The essential characteristic is that both ends know what's going on, whatever that might be.

The key here is that when a connection request is received on some port, the reply handshake includes information about the socket created to service the particular requester. Subsequent communication takes place through that (private) socket connection, not the public port connection on which the service continues to listen for connection requests.

Diplex answered 19/8, 2015 at 18:30 Comment(3)
A port is not a 'public socket', and a socket is not a 'private port'. The reply handshake contains no such thing as 'information about the socket', and subsequent communication happens between the same local and remote IP address and port as the connection request. See RFC 793. Answer is complete nonsense.Francis
@EJP: I'm sorry that you didn't like how I phrased my answer, or perhaps didn't understand it. But it's not "complete nonsense". When the server executes the accept() routine, the process forks and allocates a new socket for the private use of that connection. The original process continues to listen on the socket indexed by the port number on which the connection was requested. If you still think my answer is nonsense, I'd urge you to read Stevens's Unix Network Programming.Diplex
None of this irrelevant waffle addresses what I actually wrote. The words I quoted from your post are unsupported by RFC 793, and the only adequate response to that is to provide a supporting citation from that document. Stevens is not a normative reference, although there is nothing there either that supports your statement.Francis
P
-2

A connection socket (fd) is presented for local address + local port + peer address + peer port. Process recv/send data via socket abstract. A listening socket (fd) is presented for local address + local listening port. Process can accept new connection via socket.

Pathoneurosis answered 28/1, 2010 at 8:37 Comment(1)
Please don't think that adding arbitrary boldface everywhere is a substitute for expressing yourself clearly and correctly.Francis
B
-4

A socket allows to the communication between two applications in a single machine or two machine. actually it is like door. if the door opens there can be a connection between the process or application that are inside the door and outside the door.

There are 4 types of sockets:

  • stream sockets
  • datagram sockets
  • raw sockets
  • sequential packet sockets.

Sockets are mostly used in client-server applications. The port identifies different end points on a network address. It contains a numerical value. As overall a socket is a combination of a port and a network address.

Bookerbookie answered 5/3, 2015 at 8:57 Comment(1)
A port is a numerical value. Not much understanding conveyed here.Francis

© 2022 - 2024 — McMap. All rights reserved.