closesocket function (winsock.h)
The closesocket function closes an existing socket.
Syntax
Parameters
A descriptor identifying the socket to close.
Return value
If no error occurs, closesocket returns zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError.
Error code | Meaning |
---|---|
WSANOTINITIALISED | A successful WSAStartup call must occur before using this function. |
WSAENETDOWN | The network subsystem has failed. |
WSAENOTSOCK | The descriptor is not a socket. |
WSAEINPROGRESS | A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function. |
WSAEINTR | The (blocking) Windows Socket 1.1 call was canceled through WSACancelBlockingCall. |
WSAEWOULDBLOCK | The socket is marked as nonblocking, but the l_onoff member of the linger structure is set to nonzero and the l_linger member of the linger structure is set to a nonzero timeout value. |
Remarks
The closesocket function closes a socket. Use it to release the socket descriptor passed in the s parameter. Note that the socket descriptor passed in the s parameter may immediately be reused by the system as soon as closesocket function is issued. As a result, it is not reliable to expect further references to the socket descriptor passed in the s parameter to fail with the error WSAENOTSOCK. A Winsock client must never issue closesocket on s concurrently with another Winsock function call.
Any pending overlapped send and receive operations ( WSASend/ WSASendTo/ WSARecv/ WSARecvFrom with an overlapped socket) issued by any thread in this process are also canceled. Any event, completion routine, or completion port action specified for these overlapped operations is performed. The pending overlapped operations fail with the error status WSA_OPERATION_ABORTED.
An application should not assume that any outstanding I/O operations on a socket will all be guaranteed to completed when closesocket returns. The closesocket function will initiate cancellation on the outstanding I/O operations, but that does not mean that an application will receive I/O completion for these I/O operations by the time the closesocket function returns. Thus, an application should not cleanup any resources (WSAOVERLAPPED structures, for example) referenced by the outstanding I/O requests until the I/O requests are indeed completed.
An application should always have a matching call to closesocket for each successful call to socket to return any socket resources to the system.
The linger structure maintains information about a specific socket that specifies how that socket should behave when data is queued to be sent and the closesocket function is called on the socket.
The l_onoff member of the linger structure determines whether a socket should remain open for a specified amount of time after a closesocket function call to enable queued data to be sent. This member can be modified in two ways:
The l_linger member of the linger structure determines the amount of time, in seconds, a socket should remain open. This member is only applicable if the l_onoff member of the linger structure is nonzero.
The default parameters for a socket are the l_onoff member of the linger structure is zero, indicating that the socket should not remain open. The default value for the l_linger member of the linger structure is zero, but this value is ignored when the l_onoff member is set to zero.
To enable a socket to remain open, an application should set the l_onoff member to a nonzero value and set the l_linger member to the desired timeout in seconds. To disable a socket from remaining open, an application only needs to set the l_onoff member of the linger structure to zero.
If an application calls the setsockopt function with the optname parameter set to SO_DONTLINGER to set the l_onoff member to a nonzero value, the value for the l_linger member is not specified. In this case, the timeout used is implementation dependent. If a previous timeout has been established for a socket (by previously calling the setsockopt function with the optname parameter set to SO_LINGER), this timeout value should be reinstated by the service provider.
The semantics of the closesocket function are affected by the socket options that set members of linger structure.
Hard if all data could not be sent within timeout value specified in the l_linger member.
If the l_onoff member of the LINGER structure is zero on a stream socket, the closesocket call will return immediately and does not receive WSAEWOULDBLOCK whether the socket is blocking or nonblocking. However, any data queued for transmission will be sent, if possible, before the underlying socket is closed. This is also called a graceful disconnect or close. In this case, the Windows Sockets provider cannot release the socket and other resources for an arbitrary period, thus affecting applications that expect to use all available sockets. This is the default behavior for a socket.
If the l_onoff member of the linger structure is nonzero and l_linger member is zero, closesocket is not blocked even if queued data has not yet been sent or acknowledged. This is called a hard or abortive close, because the socket’s virtual circuit is reset immediately, and any unsent data is lost. On Windows, any recv call on the remote side of the circuit will fail with WSAECONNRESET.
If the l_onoff member of the linger structure is set to nonzero and l_linger member is set to a nonzero timeout on a blocking socket, the closesocket call blocks until the remaining data has been sent or until the timeout expires. This is called a graceful disconnect or close if all of the data is sent within timeout value specified in the l_linger member. If the timeout expires before all data has been sent, the Windows Sockets implementation terminates the connection before closesocket returns and this is called a hard or abortive close.
Setting the l_onoff member of the linger structure to nonzero and the l_linger member with a nonzero timeout interval on a nonblocking socket is not recommended. In this case, the call to closesocket will fail with an error of WSAEWOULDBLOCK if the close operation cannot be completed immediately. If closesocket fails with WSAEWOULDBLOCK the socket handle is still valid, and a disconnect is not initiated. The application must call closesocket again to close the socket.
If the l_onoff member of the linger structure is nonzero and the l_linger member is a nonzero timeout interval on a blocking socket, the result of the closesocket function can’t be used to determine whether all data has been sent to the peer. If the data is sent before the timeout specified in the l_linger member expires or if the connection was aborted, the closesocket function won’t return an error code (the return value from the closesocket function is zero).
The closesocket call will only block until all data has been delivered to the peer or the timeout expires. If the connection is reset because the timeout expires, then the socket will not go into TIME_WAIT state. If all data is sent within the timeout period, then the socket can go into TIME_WAIT state.
If the l_onoff member of the linger structure is nonzero and the l_linger member is a zero timeout interval on a blocking socket, then a call to closesocket will reset the connection. The socket will not go to the TIME_WAIT state.
The getsockopt function can be called with the optname parameter set to SO_LINGER to retrieve the current value of the linger structure associated with a socket.
Here is a summary of closesocket behavior:
- If the l_onoff member of the LINGER structure is zero (the default for a socket), closesocket returns immediately and the connection is gracefully closed in the background.
- If the l_onoff member of the linger structure is set to nonzero and the l_linger member is set to zero (no timeout) closesocket returns immediately and the connection is reset or terminated.
- If the l_onoff member of the linger structure is set to nonzero and the l_linger member is set to a nonzero timeout:– For a blocking socket, closesocket blocks until all data is sent or the timeout expires.
– For a nonblocking socket, closesocket returns immediately indicating failure.
For additional information please see Graceful Shutdown, Linger Options, and Socket Closure for more information.
Notes for IrDA Sockets
Keep the following in mind:
- The Af_irda.h header file must be explicitly included.
- The standard linger options are supported.
- Although IrDA does not provide a graceful close, IrDA will defer closing until receive queues are purged. Thus, an application can send data and immediately call the socket function, and be confident that the receiver will copy the data before receiving an FD_CLOSE message.
Notes for ATM
The following are important issues associated with connection teardown when using Asynchronous Transfer Mode (ATM) and Windows Sockets 2:
- Using the closesocket or shutdown functions with SD_SEND or SD_BOTH results in a RELEASE signal being sent out on the control channel. Due to ATM’s use of separate signal and data channels, it is possible that a RELEASE signal could reach the remote end before the last of the data reaches its destination, resulting in a loss of that data. One possible solutions is programming a sufficient delay between the last data sent and the closesocket or shutdown function calls for an ATM socket.
- Half close is not supported by ATM.
- Both abortive and graceful disconnects result in a RELEASE signal being sent out with the same cause field. In either case, received data at the remote end of the socket is still delivered to the application. See Graceful Shutdown, Linger Options, and Socket Closure for more information.
WindowsВ PhoneВ 8: This function is supported for Windows Phone Store apps on WindowsВ PhoneВ 8 and later.
WindowsВ 8.1 and Windows ServerВ 2012В R2: This function is supported for Windows Store apps on WindowsВ 8.1, Windows ServerВ 2012В R2, and later.
Viewing and killing TCP IP connections Windows
Many time in troubleshooting or needing to view network traffic information or connection information, seeing your TCP/IP connections in Windows can provide valuable insight into problems or issues that may be going on in Windows with connectivity. Also, viewing connection information is a great way to narrow down on possible backdoor traffic to a workstation if malware is suspected. In this guide, we want to look at several tools and utilities to both view connection information as well as kill TCP connections in Windows that may be problematic or malicious.
Windows itself has many really nice tools built-in that will enable you to see TCP and UDP connections right out of the box via the commandline. Especially the later versions of Windows which include Powershell expand these capabilities as well.
Commandline Tools
Powershell
With powershell we have a whole new array of commandlets to peer inside of and control what is going on with Network connections in Windows. There are two commands in general among others that provide really powerful monitoring inside of Powershell and that is the get-nettcpconnection and get-udpendpoint. Take a look at the whole list of new powershell commands for monitoring and controlling TCP activity here: https://technet.microsoft.com/en-us/library/hh826123.aspx
Get-NetTcpConnection – cmdlet gets current TCP connections. Use this cmdlet to view TCP connection properties such as local or remote IP address, local or remote port, and connection state.
Get-NetUDPEndpoint – gets current statistics for a UDP endpoint. The cmdlet returns UDP end point properties, such as local and remote UDP ports. If you do not specify any parameters, the cmdlet gets statistics for all UDP end points.
Netstat
Displays active TCP connections, ports on which the computer is listening, Ethernet statistics, the IP routing table, IPv4 statistics (for the IP, ICMP, TCP, and UDP protocols), and IPv6 statistics (for the IPv6, ICMPv6, TCP over IPv6, and UDP over IPv6 protocols). Used without parameters, netstat displays active TCP connections.
Below the command was issued netstat -ano
With the PID information you see above in the netstat output, you can use this number to correlate with PID information in Task Manager to identify the exact process and kill if need be.
Wkillcx is a small command-line utility to close any TCP connection under Windows XP/Vista/Seven as well as Windows Server 2003/2008. This is a great little commandline program that allows you to kill the remote IP:port connection information without knowing the PID. You simply issue the command, feed the appropriate connection information, it searches for that connection and kills it. Download wkillcx here: https://wkillcx.sourceforge.net/
GUI Tools
Along with the commandline tools included in Windows there are also a couple of really nice GUI tools that allow ones to see TCP activity as well as kill those TCP connections via killing the process that is spawning the TCP connections.
TCPView
TCPView is a Windows SysInternals Tool that is designed to basically show detailed listings of all TCP and UDP endpoints on your system, including the local and remote addresses and state of TCP connections. The download of the utility also includes a commandline version of the tool in tcpvcon. Download TCPView here: https://technet.microsoft.com/en-us/sysinternals/bb897437.aspx
Another really nice feature of TCPView is that you can right-click on any connection entry and then Kill the process that is using it:
Microsoft Message Analyzer 1.0
Microsoft Message Analyzer is a new tool for capturing, displaying, and analyzing protocol messaging traffic and other system messages. This is a relatively new tool that also can import data from the legacy Microsoft Network Protocol Analyzer 3.4.
This is a more full blown protocol analyzer, but can do many of the basic things we are referring too in the above guide. Download the Microsoft Message Analyzer here: https://www.microsoft.com/en-us/download/details.aspx?id=40308
Final Thoughts
Using the tools listed above, one can view network connection information via either the commandline or using GUI tools. This is extremely helpful when you are tracking down a rogue connection or a problematic process that has network hooks.