". Net 4.0 getting started with network development"-what is the IP address? (Lower)

Source: Internet
Author: User
". Net 4.0 getting started with network development series "--

What is the IP address? (Lower)

 

". Net 4.0 getting started with network development"-what is the IP address? (I)

 

 

 

4. IP endpoint

Now we will introduce the most important concept in. NET network development-IP endpoint, which is represented by the ipendpoint type in the. NET base class library.

To understand it, you must start with TCP/IP.

As mentioned above, all computers connected to the network must have a unique IP address, which is used to partition different computers on the network. The problem is that a network computer may run.MultipleNetwork applications, which may use the same network interface to receive (or send) data from the network and share the same IP address. In this case, how do you forward data packets sent to the host to the real "demander "?

To solve this problem, the TCP/IP protocol designer introduced the concept of "Port", specifying that each application that provides network services must specify a "Port ", different network applications cannot use the same port.

See the following TCP packet structure:

 

Figure 4

 

Each TCP packet contains two ports (each port occupies two bytes and is a 16-bit binary value. Therefore, the maximum port value is 1 to the power of 2, is 65535 ). Source Port indicates the port used by the network application that sends this packet, and destination port indicates the port used by the network application of the receiver.

In this way, the recipient's computer can forward this packet to a real network application based on the destination port.

On Windows, the TCP/IP Driver (tcpip. sys in the \ windows \ system32 \ drivers folder) in the operating system kernel is responsible for processing TCP packets.

The port problem is solved, but we do not see the IP address in the TCP packet? Without this address, How do I know which computer should I send data packets?

The method is as follows.

Because the TCP protocol is built on the IP protocol, the TCP packet is carried by the IP packet (figure 5 ).

 

Figure 5

 

Figure 5 clearly shows the Host IP address (source IP address) that sends the packet and the Host IP address (destination IP address) that receives the packet.

The data section in Figure 5 contains TCP packets.

It can be seen that the IP address and port uniquely identify the network application in a network. We call this combination "ip endpoint )", an IP endpoint is an access point of a network service.

Tip:

Similarly, in WCF, there is also a service endpoint (serviceendpoint), which represents the access point of a WCF Service. Have you seen the connection between various fields of software technology?

 

In. in. net, the ipendpoint class is used to represent an IP endpoint (figure 6), which is derived from the abstract base class endpoint. Pay attention to its three attributes (address \ addressfamily \ port) important information.

 

Figure 6

 

In. NET network applications, a socket object must be bound to an ipendpoint object.

For convenience, we have compiled a static method getremotemachineipendpoint and added it to the addresshelper static class described earlier:

 

// Generate valid remote host access endpoints in interactive mode, applicable to console programs
Public static ipendpoint getremotemachineipendpoint ()
{
Ipendpoint IEP = NULL;
Try
{
Console. Write ("Enter the IP address of the remote host :");
IPaddress address = IPaddress. parse (console. Readline ());
Console. Write ("enter the port number opened by the remote host :");
Int Port = convert. toint32 (console. Readline ());
If (Port> 65535 | Port <1024)
Throw new exception ("the port number should be an integer in the range ");
IEP = new ipendpoint (address, Port );
}
Catch (argumentnullexception)
{
Console. writeline ("the input data is incorrect! ");
}
Catch (formatexception)
{
Console. writeline ("the input data is incorrect! ");
}
Catch (exception ex)
{
Console. writeline (ex. Message );
}
Return IEP;
}

 

 

The following example will use this method to create a large number of IP endpoints for socket binding.

5. Which port can I use?

In actual development, you often need to specify a port for a network service dynamically to avoid conflicts with some important network service programs (for example, port 80 is fixed as used by the Web server) generally, this port must be in the range.

Now the question is how to select an unused port from it? You must know that there may be multiple network applications running on a computer, and they may be different in different time periods.

IPaddress. any can be used when a socket object is bound with an IPaddress. when the any object is assigned a port number of 0, Windows automatically assigns it an unused port number. When the socket object is no longer used and can be recycled, this port can be reused.

Therefore, we can get the following ideas:

Create a socket object, bind it to the IPaddress. Any object, extract the port allocated by the system, and then destroy the socket object.

The socket object implements the idisposable interface, so the Using Keyword can be used to automatically recycle the resources it occupies:

Below are the code snippets we have written:

Public static int getoneavailableportinlocalhost ()
{
Ipendpoint Ep = new ipendpoint (IPaddress. Any, 0 );
Using (socket tempsocket = new socket (addressfamily. InterNetwork,
Sockettype. Stream, protocoltype. TCP ))
{
Tempsocket. BIND (EP );
Ipendpoint ipep = tempsocket. localendpoint as ipendpoint;
Return ipep. port;
}
}

Tip:

An object implements the idisposable interface with a lot of attention ,. for this purpose, "idisposable programming mode" is designed. For more information, see 《. section 4.0 of net 5.5 Object-Oriented Programming

 

Now, you can call addresshelper. getoneavailableportinlocalhost () to obtain an available port at any time in your application!

But don't be so happy!

Have you considered two network applications (or two threads of the same application) simultaneously calling the above method to obtain available ports?

At this time, it cannot be guaranteed that the two calls of this method will return different ports. If two socket objects attempt to bind to the same ipendpoint, A socketexception asynchronous occurs.

Therefore, we need a thread synchronization method that can span the process boundary.

The named mutex synchronization object can solve this problem. The corrected code is as follows:

// Obtain the currently available port number of the local machine. This method is thread-safe.
Public static int getoneavailableportinlocalhost ()
{
Mutex CTX = new mutex (false, "mynetworklibrary. addresshelper. getoneavailableport ");
Try
{
CTX. waitone ();
Ipendpoint Ep = new ipendpoint (IPaddress. Any, 0 );
Using (socket tempsocket = new socket (
Addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP ))
{
Tempsocket. BIND (EP );
Ipendpoint ipep = tempsocket. localendpoint as ipendpoint;
Return ipep. port;
}
}
Finally
{
CTX. releasemutex ();
}
}

 

Tip:

《. Section 17.3.2 of net 4.0 object-oriented programming describes in detail how to use mutex objects, section 15.3.5 describes how to use the naming mutex object to implement the "Singleton mode" of an application (that is, this application cannot start two processes at the same time ), and how to use it to present the "notification mechanism" between processes ". It is recommended that you learn by comparison.

Strictly speaking, unless mutex "protects" the available port numbers and subsequent socket objects together, the modified Code above may still obtain the same port number, however, this possibility is very low. Even if an exception occurs, you can easily use the exception capture method to handle the socket object binding exception and try again to bind it to a new available port.

Now, let's write this article here.

Leave a assignment for the reader:

1. Use Visual Studio to create the class library project mynetworklibrary Based on the content described in this article, and encapsulate the getlocalhostipv4addresses (), getremotemachineipendpoint (), getoneavailableportinlocalhost () methods into the addresshelper static class, the examples in the following article will call them.

2. The net base class library provides a ping component to detect network connectivity. Learn how to use it through msdn first.

The next article, "I am in the" network "center (for the time being), will introduce this content.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.