《C#网络应用编程 第2版 习题答案作者 马骏 第03章 IP地址转换与网卡信息检测习题解答》由会员分享,可在线阅读,更多相关《C#网络应用编程 第2版 习题答案作者 马骏 第03章 IP地址转换与网卡信息检测习题解答(4页珍藏版)》请在金锄头文库上搜索。
1、第02章 IP地址转换与网卡信息检测n 习题3 参考解答1、使用DNS类和IPHostEntry类创建一个如图3-6所示的域名解析器。用户输入主机名或者DNS域名以后,能在下面的列表框中显示与主机或者DNS域名对应的IP地址和别名。图3-6 设计界面【解答】1) 主要源程序如下:using System.Net;private void button1_Click(object sender, EventArgs e) try this.Cursor = Cursors.WaitCursor; /解析主机名 IPHostEntry IPinfo = Dns.GetHostEntry(textB
2、ox1.Text); /清空列表框 listBox1.Items.Clear(); listBox2.Items.Clear(); /显示IP地址 foreach (IPAddress IP in IPinfo.AddressList) listBox1.Items.Add(IP.ToString(); /显示别名 foreach (string alias in IPinfo.Aliases) listBox2.Items.Add(alias); /显示主机名 textBox2.Text = IPinfo.HostName; catch (Exception ex) MessageBox.S
3、how(ex.Message); finally this.Cursor = Cursors.Default; 2、参考例3-3的运行界面,编写程序实现获取本机TCP连接统计信息。【解答】1) 主要源程序如下:private void FormIPGlobalStatistics_Load(object sender, EventArgs e) IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties(); TcpConnectionInformation connections = properties.
4、GetActiveTcpConnections(); foreach (TcpConnectionInformation t in connections) listBoxResult.Items.Add(Local endpoint: + t.LocalEndPoint.Address); listBoxResult.Items.Add(Remote endpoint: + t.RemoteEndPoint.Address); listBoxResult.Items.Add(State: + t.State); 2) 运行结果如图3-7所示。图3-7 设计界面3、什么是编码?什么是解码?为什
5、么要对字符进行编码和解码?.NET框架提供了哪些用于字符编码和解码的类?【解答】在网络通信中,很多情况下通信双方传达的都是字符信息。但是,字符信息并不能直接从网络的一端传递到另一端,这些字符信息首先需要被转换成一个字节序列后才能在网络中传输,将字符序列转换为字节序列的过程称为编码。当这些字节传送到网络的接收方时,接收方需反过来将字节序列再转换为字符序列,这种过程称为解码。NET Framework提供了哪些用于字符编码和解码的类有Encoding、Encoder、Decoder。Encoding类位于System.Text命名空间中,主要用于在不同的编码和Unicode之间进行转换。在网络传输
6、和文件操作中,如果数据量比较大,需要划分为较小的块,此时可能出现一个数据块的末尾是一个不匹配的高代理项,而与其匹配的低代理项则位于下一个数据块中。对于这种情况,直接使用Encoding类的GetBytes方法编写程序就比较麻烦。此时,可以利用Encoder类及Decoder类轻松地解决这个问题。4、参考例3-5的运行界面,编写程序利用Encoding类实现编码及解码。【解答】using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawin
7、g;using System.Text;using System.Windows.Forms;using System.Net.NetworkInformation;namespace EncoderDecoderExample public partial class FormEncoderDecoder : Form public FormEncoderDecoder() InitializeComponent(); private void buttonRun_Click(object sender, EventArgs e) /编码 String strCodeType = boBox
8、Type.SelectedItem.ToString(); Encoding encoder = Encoding.GetEncoding(strCodeType); Byte bytes = encoder.GetBytes(this.textBoxOldText.Text); textBoxEncoder.Text = Convert.ToBase64String(bytes); /解码 Encoding decoder = Encoding.GetEncoding(strCodeType); string strResult = decoder.GetString(bytes); textBoxDecoder.Text = strResult; private void FormEncoderDecoder_Load(object sender, EventArgs e) /显示现有的编码类型 foreach (EncodingInfo ei in Encoding.GetEncodings() Encoding en = ei.GetEncoding(); boBoxType.Items.Add(en.HeaderName); boBoxType.SelectedIndex = 0; 3