Network Programming in .NET With C# and Visual Basic .NET phần 8 doc

56 505 1
Network Programming in .NET With C# and Visual Basic .NET phần 8 doc

Đ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

13.4 Physical network tapping 373 Chapter 13 The InterfaceStatistics class, as returned by GetInterfaceStatis- tics , is described in Table 13.16 (all properties return int64 unless other- wise specified). Mtu Determines the maximum transmission unit of the interface. Returns int64. Name Gets a name for the interface. Returns string. OperationalStatus Gets the operational status of the interface. Returns OperationalStatus. Type Determines the interface hardware. Returns InterfaceType (e.g., modem, ISDN, ADSL, Ethernet, etc.). Table 13.16 Significant members of the InterfaceStatistics class . Method or Property Purpose BytesReceived Gets the number of bytes received BytesSent Gets the number of bytes sent IncomingPacketsDiscarded Gets the number of incoming packets discarded IncomingPacketsWithErrors Gets the number of incoming packets with errors IncomingUnknownProtocolPackets Gets the number of incoming unknown protocol packets NonUnicastPacketsReceived Gets the number of non-Unicast packets received NonUnicastPacketsSent Gets the number of non-Unicast packets sent OutgoingPacketsDiscarded Gets the number of outgoing packets discarded OutgoingPacketsWithErrors Gets the number of outgoing packets with errors OutputQueueLength Gets the number of output queue length Table 13.15 Significant members of the NetworkInterface class (continued). Method or Property Purpose 374 13.4 Physical network tapping The IPAddressInformation class, as returned by GetIPAddressInfor- mation , is described in Table 13.17. The IPv4Properties class, as returned by GetIPv4Properties, is described in Table 13.18. These properties may be alternatively ascertained on an adapter-by-adapter basis through the GetAdaptersInfo Windows IP Helper API function. Speed Gets the speed of the interface UnicastPacketsReceived Gets the number of Unicast packets received UnicastPacketsSent Gets the number of Unicast packets sent Table 13.17 Significant members of the IPAddressInformation class. Method or Property Purpose Address Gets the IP address DnsEligible Determines if the address is eligible for DNS Transient Determines if the address is transient Table 13.18 Significant members of the IPv4Properties class . Method or Property Purpose GetDhcpServerAddresses Retrieves the local DHCP server addresses. Returns IPAddress[]. GetGatewayAddresses Retrieves the local gateway addresses. Returns IPAddress[]. GetWinsServersAddresses Retrieves the local WINS servers addresses. Returns IPAddress[]. AutomaticPrivateAddressingActive Determines if automatic private addressing is active. Returns Boolean. Table 13.16 Significant members of the InterfaceStatistics class (continued). Method or Property Purpose 13.4 Physical network tapping 375 Chapter 13 The TcpStatistics class, as returned by GetTcpStatistics, is described in Table 13.19 (all properties return int64 unless otherwise stated). This is equivalent to calling the GetTcpTable Windows IP Helper API, or running NETSTAT -p tcp -a from the command line. AutomaticPrivateAddressingEnabled Determines if automatic private addressing is enabled. Returns Boolean. DhcpEnabled Determines if DHCP is enabled. Returns Boolean. RoutingEnabled Determines if routing is enabled. Returns Boolean. UsesWins Determines if the computer uses WINS. Returns Boolean. Table 13.19 Significant members of the TcpStatistics class . Method or Property Purpose ConnectionsAccepted Determines the number of connections accepted ConnectionsInitiated Determines the number of connections ini- tiated CumulativeConnections Determines the number of cumulative con- nections CurrentConnections Determines the number of current connec- tions ErrorsReceived Determines the number of errors received FailedConnectionAttempts Determines the number of failed connection attempts MaximumConnections Determines the maximum number of con- nections MaximumTransmissionTimeOut Determines the maximum transmission time out Table 13.18 Significant members of the IPv4Properties class (continued). Method or Property Purpose 376 13.5 Conclusion The UdpStatistics class, as returned by GetUdpStatistics, is described in Table 13.20 (all properties return int64 unless otherwise stated). This is equivalent to the GetUdpStatistics Windows IP Helper API function. 13.5 Conclusion This chapter has shown three different means to tap nonintrusively into the data that flows between computers. When local system traffic monitoring is all that is required, then use of the pure .NET implementation is highly rec- ommended, but for an enterprisewide implementation, then PacketX com- MinimumTransmissionTimeOut Determines the minimum transmission time out ResetConnections Determines the number of reset connections SegmentsReceived Determines the number of segments received SegmentsResent Determines the number of segments resent SegmentsSent Determines the number of segments sent SegmentsSentWithReset Determines the number of segments sent with reset Table 13.20 Significant members of the UdpStatistics class. Method or Property Purpose DatagramsReceived Determines the number of datagrams received DatagramsSent Determines the number of datagrams sent IncomingDatagramsDiscarded Determines the number of incoming data- grams discarded IncomingDatagramsWithErrors Determines the number of incoming data- grams with errors UdpListeners Determines the number of active UDP lis- teners Table 13.19 Significant members of the TcpStatistics class (continued). Method or Property Purpose 13.5 Conclusion 377 Chapter 13 bined with WinPCap is possibly the best option. Where financial constraints prevent the use of a third-party commercial component, then rvPacket will probably point you in the right direction. It would be impossible to document the format of every protocol that could exist on a network, so only IP and TCP have been described in this chapter. Interested readers are advised to consult the relevant RFC for infor- mation on any specific protocol. The next chapter deals with a form of telecommunication that has been with us since the 1880s (i.e., the ubiquitous phone call); however, the chap- ter is taken from a Computer Telephony Integration (CTI) developer’s per- spective. Prepare to be introduced to the telephony API. This page intentionally left blank 379 14 Adding Digital Telephony 14.1 Introduction If you call any large cinema looking for times for films, you will undoubt- edly be forwarded to an automated system that tells you when each film is on. This system is made possible by digital telephony. Computer Telephony Integration, or CTI, systems routinely cost $10,000 and upward for enterprise-scale systems. The high cost is largely a result of the misconceived idea that any telephony system requires loads of specialized hardware and, thus, is out of reach for the humble developer. In fact, you can put a simple system together using no more than a cheap modem. Any company that employs staff to answer phone calls can save money by implementing a CTI system. Such a system can be used to route calls to different departments automatically or to match a caller with customer ID and associated purchase history. This chapter is mainly devoted to one rather large code example built up in three sections. The first section explains how to pick up and drop a call. The following section explains how to detect key presses on the remote handset, and the chapter concludes with a demonstration of how to play back audio to the caller. Note: You will need a voice modem and phone line to test the following examples. Access to a second phone (such as a mobile phone) is beneficial. Calls made from any phone line may incur charges if the line is opened. 380 14.2 Basic telephony 14.2 Basic telephony This chapter is focused on using the telephony API, but it is possible to control a modem by issuing COM port commands. These will provide the ability to dial telephone numbers and control the physical connection to the phone line. Even if your modem is internal or connected via USB, it will always be mapped to a COM port. To discover the number of this COM port, you can look at Start →→ →→ Control Panel →→ →→ phone and Modem options →→ →→ Modems. Under the Attached To tab will be the number of the COM port to which the modem is attached. Any command that is sent to this COM port will be interpreted by the modem. A list of common AT commands shown in Table 14.1. The responses the modem will send back shown in Table 14.2. Table 14.1 AT commands. AT Command Purpose ATDT< phone number ><enter> Dials the specified phone number using touch-tone dialing. A comma in the number represents a pause, a W waits for a second dial tone, and an @ waits for a five-second silence. ATPT< phone number ><enter> Dials the specified number using pulse dialing. AT S0=< number > Picks up the line after the specified number of rings. +++ Drop line. Table 14.2 Modem responses . Response Meaning O K The command has executed without errors. CONNECT A connection to the remote phone has been made. RING An incoming call is detected. NO CARRIER No carrier signal has been detected (in GSM modems, this can mean that there is no network). ERROR The command is not understood. 14.2 Basic telephony 381 Chapter 14 To implement a simple phone dialer in .NET, open Visual Studio .NET and start a new Windows forms project. Right-click on the toolbox and click Customize Toolbox (or Add/Remove Items in Visual Studio .NET 2003). Click on the COM Controls tab, and then add the Microsoft Communications control ( MSCOMM.OCX ). Drag this onto the form, and set the comport property to the COM port number to which your modem is connected. Add a button to the form, named btnPhone , click it, and add this code: C# private void btnPhone_Click(object sender, System.EventArgs e) { axMSComm1.PortOpen=true; axMSComm1.Output="ATDT00353877519575\r\n"; } VB.NET Private Sub btnPhone_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) axMSComm1.PortOpen=True axMSComm1.Output="ATDT00353877519575" + vbcrlf End Sub Note: Running the code listed above may incur phone charges. It is advis- able to change the phone number listed (00353877519575) to some other, less expensive number. Only one program can control each COM port at a time. This code will fail if you are using the modem at the time. Several settings are associated with a COM port; in this case, however, the default parameters (9600 NO DIAL TONE There is no dial tone on the phone line. BUSY The remote end is too busy to take the call. NO ANSWER The remote end did not take the call. Table 14.2 Modem responses (continued). Response Meaning 382 14.3 Listening for incoming phone calls baud, no parity, 8 data bits, 1 stop bit—or “9600,n,8,1”) are suitable for communication with a modem. When the modem begins communication at full speed, it will use a baud rate of 56 Kbps. This can be set using the settings property of the Microsoft communications control. 14.3 Listening for incoming phone calls You can only do a certain number of things with a modem by sending com- mands back and forth via a COM port. In order to develop serious applica- tions, you have to use the Telephony Application Programming Interface (TAPI). The TAPI libraries were designed with C++ in mind, not .NET, so there is a steep learning curve. It is worthwhile to evaluate the various com- mercial components available before tinkering with low-level TAPI code. A few interesting Web sites, such as www.shrinkwrapvb.com and www.pron- exus.com, contain a wealth of information on TAPI. The overall architecture of TAPI is modeled on a collection of phone lines that are connected to the computer. Not all of these phone lines are physical connections. Some of them are software representations of phone lines used for various internal processes. Each phone line may be opened or closed, which is analogous to a phone being on or off hook. An open phone line does not necessarily incur charges, unless a call is active. When a phone line is open (off hook), it generates callbacks detailing any event that has happened on the line, such as an incoming call. A call- back is simply a function that is called asynchronously by an underlying process. When an incoming call is detected, the callback will contain a handle that can be passed to a function that accepts the call. At this point, call charges are applied to the line by the phone operator. Once the call is open, the modem behaves like a rudimentary audio device, which can play and receive basic audio. The line can still generate callbacks, such as a line dropping or the detection of the remote user pressing digits on the phone’s keypad. When the call is dropped, the line remains open, but the modem can no longer function as an audio device. Phone charges will no longer be applied when the call is dropped. Callbacks will be generated until the line is closed. Note: Warning: If a line is not closed before the application exits, the com- puter may need to be restarted before the line can be reopened. [...]... closes This prevents Windows from crashing if your application does not shut down cleanly 14.3 Listening for incoming phone calls 391 C# public delegate int LineCallBackDelegate(int dwDevice, int dwMessage, int dwInstance, int dwParam1, int dwParam2, int dwParam3); public static int LineCallBack(int dwDevice, int dwMessage, int dwInstance, int dwParam1, int dwParam2, int dwParam3) { string msgEvent="";... int dwUUISendUserUserInfoSize; int dwUUICallInfoSize; linedialparams MinDialParams; linedialparams MaxDialParams; linedialparams DefaultDialParams; int dwNumTerminals; int dwTerminalCapsSize; int dwTerminalCapsOffset; int dwTerminalTextEntrySize; int dwTerminalTextSize; int dwTerminalTextOffset; int dwDevSpecificSize; int dwDevSpecificOffset; int dwLineFeatures; // TAPI v1.4 string bBytes; } [DllImport("Tapi32.dll",SetLastError=true)]... static int hTAPI; static int lNumLines; static int hLine; static linedevcaps lpLineDevCaps; static frmTAPI userInterface; const int TAPIVERSION = 0x10004; const short LINECALLPRIVILEGE_OWNER = 0x4; const short LINECALLPRIVILEGE_MONITOR = 0x2; const short LINEMEDIAMODE_AUTOMATEDVOICE = 0x8; const int LINE_LINEDEVSTATE = 8; const int LINE_CALLSTATE = 2; const int LINECALLSTATE_OFFERING = 0x2; const int LINECALLSTATE_ACCEPTED... public int dwUsedSize; public int dwProviderInfoSize; public int dwProviderInfoOffset; public int dwSwitchInfoSize; public int dwSwitchInfoOffset; public int dwPermanentLineID; public int dwLineNameSize; public int dwLineNameOffset; public int dwStringFormat; public int dwAddressModes; public int dwNumAddresses; public int dwBearerModes; public int dwMaxRate; public int dwMediaModes; public int dwGenerateToneModes;... static extern int lineGetDevCaps (int hLineApp, int dwDeviceID, int dwAPIVersion, int dwExtVersion, ref linedevcaps lpLineDevCaps); [DllImport("Tapi32.dll",SetLastError=true)] public static extern int lineSetStatusMessages (int hLine, int dwLineStates, int dwAddressStates); [DllImport("Tapi32.dll",SetLastError=true)] public static extern int lineDrop (int hCall, string lpsUserUserInfo, int dwSize);... extern int lineAnswer (int hCall, ref string lpsUserUserInfo, int dwSize); [DllImport("Tapi32.dll",SetLastError=true)] public static extern int lineInitialize (ref int hTAPI,int hInst, LineCallBackDelegate fnPtr , ref int szAppName, ref int dwNumLines); [DllImport("Tapi32.dll",SetLastError=true)] public static extern int lineNegotiateAPIVersion(int hTAPI, int dwDeviceID, int dwAPILowVersion, int dwAPIHighVersion,... dwAPILowVersion, int dwAPIHighVersion, ref int lpdwAPIVersion, ref lineextensionid lpExtensionID); Chapter 14 386 14.3 Listening for incoming phone calls [DllImport("Tapi32.dll",SetLastError=true)] public static extern int lineOpen (int hLineApp, int dwDeviceID, ref int lphLine, int dwAPIVersion, int dwExtVersion, ref int dwCallbackInstance, int dwPrivileges, int dwMediaModes, ref int lpCallParams); [DllImport("Tapi32.dll",SetLastError=true)]... dwProviderInfoOffset As Integer Dim dwSwitchInfoSize As Integer Dim dwSwitchInfoOffset As Integer Dim dwPermanentLineID As Integer Dim dwLineNameSize As Integer Dim dwLineNameOffset As Integer Dim dwStringFormat As Integer Dim dwAddressModes As Integer Dim dwNumAddresses As Integer Dim dwBearerModes As Integer Dim dwMaxRate As Integer Dim dwMediaModes As Integer Dim dwGenerateToneModes As Integer Dim dwGenerateToneMaxNumFreq... Dim MinDialParams As linedialparams Dim MaxDialParams As linedialparams Dim DefaultDialParams As linedialparams Dim dwNumTerminals As Integer Dim dwTerminalCapsSize As Integer Dim dwTerminalCapsOffset As Integer Dim dwTerminalTextEntrySize As Integer Dim dwTerminalTextSize As Integer Dim dwTerminalTextOffset As Integer Dim dwDevSpecificSize As Integer Dim dwDevSpecificOffset As Integer Dim dwLineFeatures... 0x4; const int LINECALLSTATE_DISCONNECTED = 0x4000; public struct linedialparams { int dwDialPause; int dwDialSpeed; Chapter 14 384 14.3 Listening for incoming phone calls int dwDigitDuration; int dwWaitForDialtone; } public struct lineextensionid { int dwExtensionID0; int dwExtensionID1; int dwExtensionID2; int dwExtensionID3; } public struct linedevcaps { public int dwTotalSize; public int dwNeededSize; . cleaning up any resources. 14.3 Listening for incoming phone calls 391 Chapter 14 C# public delegate int LineCallBackDelegate(int dwDevice, int dwMessage, int dwInstance, int dwParam1, int. public int dwSwitchInfoOffset; public int dwPermanentLineID; public int dwLineNameSize; public int dwLineNameOffset; public int dwStringFormat; public int dwAddressModes; public int dwNumAddresses; . dwNumTerminals; public int dwTerminalCapsSize; public int dwTerminalCapsOffset; public int dwTerminalTextEntrySize; public int dwTerminalTextSize; public int dwTerminalTextOffset; public int

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

Từ khóa liên quan

Mục lục

  • 13 Analyzing Network Packets

    • 13.5 Conclusion

    • 14 Adding Digital Telephony

      • 14.1 Introduction

      • 14.2 Basic telephony

      • 14.3 Listening for incoming phone calls

      • 14.4 DTMF tones

      • 14.5 Audio playback

        • 14.5.1 Audio playback over TAPI

        • 14.6 Conclusion

        • 15 Message Queues

          • 15.1 Introduction

          • 15.2 MSMQ

          • 15.3 Implementing a message queue

            • 15.3.1 Queuing complex objects

Tài liệu cùng người dùng

Tài liệu liên quan