1. Trang chủ
  2. » Công Nghệ Thông Tin

Network Programming in .NET With C# and Visual Basic .NET phần 7 ppsx

56 1,3K 1

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 56
Dung lượng 721,44 KB

Nội dung

12.3 Ping 317 Chapter 12 IcmpSendEcho sends an ICMP echo request to a host as specified in the DestAddress parameter. The format of the outgoing ping is set in the RequestOptns parameter, and details of the reply (or lack thereof) are stored in the ReplyBuffer . Go to the form and draw a textbox named tbIP and a button named btnPing . Click on the button and add the following code: C# private void btnPing_Click(object sender, System.EventArgs e) { uint LongIP; string buffer; UInt32 hIP; uint timeout; buffer = new StringBuilder().Append(' ',32).ToString(); LongIP = convertIPtoLong(tbIP.Text); hIP = PING.IcmpCreateFile(); PING.pIPo.TTL = 255; timeout = 2700; PING.IcmpSendEcho(hIP, LongIP, buffer, (uint)buffer.Length, ref PING.pIPo, ref PING.pIPe, (uint)Marshal.SizeOf(PING.pIPe) + 8, timeout); MessageBox.Show(describeResponse(PING.pIPe.Status)); } VB.NET Private Sub btnPing_Click(ByVal eventSender As _ System.Object, ByVal eventArgs As System.EventArgs) _ Handles btnPing.Click Dim LongIP As UInt32 Dim buffer As String Dim hIP As Integer Dim timeout As Short buffer = Space(32) LongIP = convertIPtoLong((tbIP.Text)) hIP = IcmpCreateFile() pIPo.TTL = 255 timeout = 2700 318 12.3 Ping IcmpSendEcho(hIP, LongIP, buffer, Len(buffer), pIPo, _ pIPe, Len(pIPe) + 8, timeout) MsgBox(describeResponse(pIPe.Status)) End Sub You may notice that the IP address is converted from a string to a Uint32 (unsigned 32-bit integer) by the ConvertIPtoLong function. This is required because the DestAddress parameter of IcmpSendEcho uses a binary representation of IP addresses. So, add in the following function to implement convertIPtoLong : C# public UInt32 convertIPtoLong(string ip) { string[] digits; digits = ip.Split(".".ToCharArray()); return Convert.ToUInt32( Convert.ToUInt32(digits[3]) * Math.Pow(2,24) + Convert.ToUInt32(digits[2]) * Math.Pow(2,16) + Convert.ToUInt32(digits[1]) * Math.Pow(2,8) + Convert.ToUInt32(digits[0])); } VB.NET Public Function convertIPtoLong(ByRef ip As String) As UInt32 Dim digits() As String digits = Split(ip, ".") convertIPtoLong = Convert.ToUInt32(digits(3) * 2 ^ 24 _ + digits(2) * 2 ^ 16 + _ digits(1) * 2 ^ 8 + _ digits(0)) End Function This function splits an IP address into its four constituent bytes, multi- plies each byte by a power of 2, and adds them together. In the case of the loop-back address 127.0.0.1, this is converted to 127 + 1 × 2 24 , or 16,777,343. You may also notice in the code above that a message box is displayed once IcmpSendEcho returns. This message could therefore describe to the user the result of the ping request. The function describeResponse per- 12.3 Ping 319 Chapter 12 forms the task of converting the rather cryptic response codes into mean- ingful phrases. Enter the following code: C# public string describeResponse(uint code) { string Rcode = ""; switch(code) { case 0 : Rcode = "Success";break; case 11001 : Rcode = "Buffer too Small";break; case 11002 : Rcode = "Dest Network Not Reachable";break; case 11003 : Rcode = "Dest Host Not Reachable";break; case 11004 : Rcode = "Dest Protocol Not Reachable";break; case 11005 : Rcode = "Dest Port Not Reachable";break; case 11006 : Rcode = "No Resources Available";break; case 11007 : Rcode = "Bad Option";break; case 11008 : Rcode = "Hardware Error";break; case 11009 : Rcode = "Packet too Big";break; case 11010 : Rcode = "Rqst Timed Out";break; case 11011 : Rcode = "Bad Request";break; case 11012 : Rcode = "Bad Route";break; case 11013 : Rcode = "TTL Exprd in Transit";break; case 11014 : Rcode = "TTL Exprd Reassemb";break; case 11015 : Rcode = "Parameter Problem";break; case 11016 : Rcode = "Source Quench";break; case 11017 : Rcode = "Option too Big";break; case 11018 : Rcode = " Bad Destination";break; case 11019 : Rcode = "Address Deleted";break; case 11020 : Rcode = "Spec MTU Change";break; case 11021 : Rcode = "MTU Change";break; case 11022 : Rcode = "Unload";break; case 11050 : Rcode = "General Failure";break; } return Rcode; } VB.NET Public Function describeResponse(ByRef code As Integer) _ As String 320 12.3 Ping Dim Rcode As String Select Case code Case 0 : Rcode = "Success" Case 11001 : Rcode = "Buffer too Small" Case 11002 : Rcode = "Dest Network Not Reachable" Case 11003 : Rcode = "Dest Host Not Reachable" Case 11004 : Rcode = "Dest Protocol Not Reachable" Case 11005 : Rcode = "Dest Port Not Reachable" Case 11006 : Rcode = "No Resources Available" Case 11007 : Rcode = "Bad Option" Case 11008 : Rcode = "Hardware Error" Case 11009 : Rcode = "Packet too Big" Case 11010 : Rcode = "Rqst Timed Out" Case 11011 : Rcode = "Bad Request" Case 11012 : Rcode = "Bad Route" Case 11013 : Rcode = "TTL Exprd in Transit" Case 11014 : Rcode = "TTL Exprd Reassemb" Case 11015 : Rcode = "Parameter Problem" Case 11016 : Rcode = "Source Quench" Case 11017 : Rcode = "Option too Big" Case 11018 : Rcode = " Bad Destination" Case 11019 : Rcode = "Address Deleted" Case 11020 : Rcode = "Spec MTU Change" Case 11021 : Rcode = "MTU Change" Case 11022 : Rcode = "Unload" Case 11050 : Rcode = "General Failure" End Select describeResponse = Rcode End Function Many of the response codes listed would be rare and would probably indicate a programming error instead of a real network error. The most common are Success and Dest host not available. C# programmers will also require the following namespaces in both the form and class file: C# using System.Text; using System.Runtime.InteropServices; 12.4 WHOIS 321 Chapter 12 To test the application, run it from Visual Studio .NET, type the IP address (not domain name!) of a well-known Web server into the box provided, and press Ping. It should respond with the message “Success” if the computer is accessible or “Dest Host Not Reachable” if it is not, as in Figure 12.2. Ping can be used for more than simply checking whether a computer is switched on or not; it can also be used to trace the route of packets over the Internet. This is achieved by sending a ping request with a TTL of 1, fol- lowed by a ping with a TTL of 2, and so on. At each hop, a router will report a dead ping request and send a packet back to the original host, which will contain the IP address of the router. This technique is used by the tracert utility. In .NET v2 (Whidbey), it is possible to retrieve statistics easily relating to the number and type of pings received and sent by your computer. Please refer to the IcmpV4Statistics class, as described in Chapter 13, for more information on this topic. 12.4 WHOIS WHOIS (“who is”) is a protocol that can be used to query the registrant of a domain name. It runs on TCP port 43 and is described definitively in RFC 954. This information includes the name and company of the person who bought the domain name, along with details of the DNS servers for that domain and the operator(s) of those servers. Despite its usefulness, WHOIS is a poorly designed protocol. There are many WHOIS servers worldwide, each of which contains a subset of all the Internet domain names. There is no way to determine from a domain name Figure 12.2 ICMP (ping) client application. 322 12.4 WHOIS which WHOIS server contains registrant information for that name. Fur- thermore, the content of WHOIS replies is not properly standardized, which makes it particularly difficult to parse replies properly. Note: Operators of WHOIS servers generally limit the number of queries per day per IP address to 100 in order to prevent data mining. Most countries have their own WHOIS server that covers the top-level domain for that country (such as .co.uk or .ie). International top-level domains such as .com, .net, and .org are stored in subsets in large WHOIS servers or allocated by central WHOIS servers on a continent-by-continent basis. A few well-known WHOIS servers are whois.networksolutions.com, whois.crsnic.net, and whois.ripe.net. To perform a WHOIS query manually, run telnet from the command prompt, and type the following: O whois.ripe.net 43 Google.de The result will be as follows (abbreviated for clarity): % This is the RIPE Whois server. % The objects are in RPSL format. % The object shown below is NOT in the RIPE database. % It has been obtained by querying a remote server: % (whois.denic.de) at port 43. %REFERRAL START domain: google.de descr: Google Inc. descr: Valentinskamp 24 descr: 20354 Hamburg descr: GERMANY nserver: ns1.google.com nserver: ns2.google.com nserver: ns3.google.com nserver: ns4.google.com status: connect 12.4 WHOIS 323 Chapter 12 changed: 20021125 170514 source: DENIC [admin-c] Type: PERSON Name: joel Fokke Address: Valentinskamp 24 City: Hamburg Pcode: 20354 Country: DE Changed: 20021023 150831 Source: DENIC [tech-c][zone-c] Type: ROLE Name: DENICoperations Address: DENIC eG Address: Wiesenhuettenplatz 26 City: Frankfurt am Main Pcode: 60329 Country: DE Phone: +49 69 27235 272 Fax: +49 69 27235 234 Email: ops@denic.de Changed: 20020621 194343 Source: DENIC %REFERRAL END Unfortunately, as mentioned earlier, the WHOIS reply is not standard- ized, so expect different fields from different WHOIS servers. Whois.Net- workSolutions.Com will return fields in this format (abbreviated reply for hotmail.com): Registrant: Microsoft Corporation (HOTMAIL-DOM) One Microsoft Way Redmond, CA 98052 US Domain Name: HOTMAIL.COM 324 12.4 WHOIS Administrative Contact: Gudmundson, Carolyn (PPUFRBYFWI) domains@microsoft.com One Microsoft Way Redmond, WA 98052 US (425) 882-8080 fax: (425) 936-7329 Technical Contact: NOC, MSN (RWJALTFZAI) msnhst@microsoft.com Note: For a bit of entertainment, look up the WHOIS entry for Microsoft.com with whois.crsnic.net. You’ll find some interesting entries made by some Linux fans! Performing a WHOIS query with .NET is easy. All that is required is to open a TCP connection on port 43, send the domain name followed by the new line character, and read back the response until the connection closes. Create a new project in Visual Studio .NET. Draw three textboxes named tbServer, tbQuery, and tbStatus, the latter having multiline set to true. A button named btnSend is also required. Click on the Send button, and add the following code: C# private void btnSend_Click(object sender, System.EventArgs e) { byte[] Query = Encoding.ASCII.GetBytes( tbQuery.Text + "\n"); TcpClient clientSocket = new TcpClient(tbServer.Text,43); NetworkStream networkStream = clientSocket.GetStream(); networkStream.Write(Query,0,Query.GetLength(0)); StreamReader Response = new StreamReader(networkStream); tbStatus.Text=Response.ReadToEnd(); networkStream.Close(); } 12.4 WHOIS 325 Chapter 12 VB.NET Private Sub btnSend_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Dim Query() As Byte = Encoding.ASCII.GetBytes _ (tbQuery.Text + vbcrlf) Dim clientSocket As TcpClient = New _ TcpClient(tbServer.Text,43) Dim networkStream As NetworkStream = _ clientSocket.GetStream() networkStream.Write(Query,0,Query.GetLength(0)) Dim Response As StreamReader = New _ StreamReader(networkStream) tbStatus.Text=Response.ReadToEnd() networkStream.Close() End Sub You will also require a reference to some namespaces needed for the string handling and networking: C# using System.Text; using System.Net; using System.Net.Sockets; using System.IO; VB.NET Imports System.Text Imports System.Net Imports System.Net.Sockets Imports System.IO To test the application, run it from Visual Studio .NET. Enter the name of a WHOIS server in the box provided, in this case whois.crsnic.net. Enter a domain name in the query box, omitting the “www” prefix. Press Send, and you should receive information about the registrant of that domain, similar to that shown in Figure 12.3. 326 12.4 WHOIS 12.4.1 Telnet In the days before GUIs, users of UNIX enjoyed the luxury of being able to control their server remotely via a command-line interface. Text-only inter- faces may be passé, but many online services are still hosted on UNIX, and where configuration changes need to be made to the server, telnet is still the defacto standard for UNIX servers. The protocol itself is straightforward: a TCP connection is opened on port 23, and this connection is persisted until one end closes the connec- tion. Generally, any character typed on the keyboard is sent to the server and any returned data is displayed on-screen as text. Telnet could be used as a back end to a remote configuration console for a UNIX product, but beyond that, it would rarely be used programmati- cally. It is, however, often used to debug servers and investigate new TCP- based protocols because all telnet clients provide the option to connect on ports other than 23. A telnet client is included with Windows. In Windows 95 and 98, the telnet client has a GUI, but XP uses a DOS-based client. If you have a Web server on your computer, you can check that telnet is operational by typing the following code at the command prompt: telnet localhost 80 GET / Figure 12.3 WHOIS client application. [...]... gather systemwide network information 13.2 IP-level network tapping Network tapping anything that runs at the IP level includes TCP/IP and UDP and everything above that, such as DNS, HTTP, FTP, and so forth At this level, you don’t need to use any special software Everything can be done natively in NET To implement a layer 3 network tap in NET, open a new project in Visual Studio NET and add a list box... data Capturing and interpreting raw network data are totally separate things Being able to recognize anomalies in the network data is the key to providing a useful tool that could be of real benefit to network managers and administrators Figure 13.2 IP-layer packet sniffer application 13.2 IP-level network tapping 345 Raw network data can appear totally unordered, with HTTP packets mixed in with NETBIOS... have the ninth byte in the header set to 6 All null (ASCII code 0) characters are displayed as spaces so that the list box does not crop the string at the first null character Finally, you need to add some standard namespaces to the code: C# using System; using System.Windows.Forms; Chapter 13 344 13.2 IP-level network tapping using using using using System.Net.Sockets; System.Net; System.Threading; System.Text;... network and looks at exactly what gets sent down the phone line when you use the Internet If you’re on a LAN, you might be surprised to see what passes through your computer without your knowledge Be warned: Read the following chapter, and you’ll never play multiplayer games on your company network again! 13 Analyzing Network Packets 13.1 Introduction Network programming is very much concerned with moving... Instrumentation, is used within a Windows intranet to provide a facility to perform simple administrative tasks remotely The main advantage this provides is that the WMI client is built into Windows, so there is no need to write or install a proprietary client, as long as the Windows Management Instrumentation service is running on the remote machine One of the main uses of WMI is to extract technical information... Chapter 12 336 12 .7 Conclusion 12 .7 Conclusion This chapter has dealt with a set of network protocols that are not suited to moving bulk data among machines, but are particularly valuable in adding features and improving the performance of distributed applications These utility protocols can be used to test quickly if machines are online, what domain names or hosts are associated with them, and who is the... System.Text; VB.NET Imports Imports Imports Imports Imports Imports System System.Windows.Forms System.Net.Sockets System.Net System.Threading System.Text To test the application, run it from Visual Studio NET, and visit a Web site using your browser You should see the raw TCP data flowing between your browser and the Web server appear in the list box, as shown in Figure 13.2 13.2.1 Interpreting raw network. .. protocol (EGP) and is used to route packets outside of a network to other people’s networks It differs from OSPF, which is used in internal networks Note: You should never have two BGP routers on the same network without support for OSPF or RIP 12.5.5 SNMP Simple network management protocol (SNMP) enables network administrators to connect and manage network devices It is being superseded with RMON, but... carries a header that is in a strictly defined binary format To define the standards involved most concisely, the tables in this chapter list the name and starting point of each field in the relevant header Every field runs contiguously with the next; thus, the length of any field can be calculated by subtracting its starting point from the following field’s starting point Because fields do not need to start at... the recipient warning of the possibility of email forgery This chapter begins with information about how to read and interpret IP-level traffic on your network It then progresses to more complex examples about how to drill down further into the network stack and extract lower-level data at the frame level The chapter concludes with information about how to use new classes introduced in NET 2.0 Whidbey . StreamReader(networkStream) tbStatus.Text=Response.ReadToEnd() networkStream.Close() End Sub You will also require a reference to some namespaces needed for the string handling and networking: C# using. SNMP Simple network management protocol (SNMP) enables network adminis- trators to connect and manage network devices. It is being superseded with RMON, but is still widely used by network devices packets outside of a network to other people’s networks. It differs from OSPF, which is used in internal networks. Note: You should never have two BGP routers on the same network with- out support

Ngày đăng: 12/08/2014, 21:20

TỪ KHÓA LIÊN QUAN