悟生慧

 

C#3.5之网络编程 简单示例

根据输入的主机地址获取主机IP地址 主机名和DNS主机名

private void button1_Click(object sender, EventArgs e)
        {
            //判断是否输入了IP地址
            if (textBox1.Text == string.Empty)
            {
                MessageBox.Show("请输入主机地址!");//aimajia2012.gotoftp2.com
                return;
            }
            else
            {
                textBox2.Text = string.Empty;
                //获取指定主机的IP地址
                IPAddress[] ips = Dns.GetHostAddresses(textBox1.Text);
                //循环访问获得的IP地址
                foreach (IPAddress ip in ips)
                {
                    textBox2.Text = ip.ToString();
                }
                textBox3.Text = Dns.GetHostName();
                //根据指定的主机名获取DNS信息
                textBox4.Text = Dns.GetHostEntry(Dns.GetHostName()).HostName;
            }
            IPAddressUse();
        }

//调用IPAddress类中的各个属性获取指定主机的IP地址信息

private void button1_Click(object sender, EventArgs e)
        {
            label5.Text = string.Empty;//初始化Label标签
            IPAddress[] ips = Dns.GetHostAddresses(textBox1.Text);
            foreach (IPAddress ip in ips)
            {
                label5.Text = "网际协议地址:" + ip.Address.ToString() + "\nIP地址的地址族:" + ip.AddressFamily.ToString() + "\n是否IPv6链接本地地址:" + ip.IsIPv6LinkLocal;
            }
        }

 

 private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = "220.166.64.67";
            //实例化IPEndPoin类对象
            IPEndPoint IPEPoint = new IPEndPoint(IPAddress.Parse(textBox1.Text), 80);
            //使用IPEndPoint类对象获取终结点的IP地址和端口号
            label5.Text = "IP地址:" + IPEPoint.Address.ToString() + "\n 端口号:" + IPEPoint.Port;
        }
//WebClient获取指定网址中的网页内容
        private void button2_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = string.Empty;
            //实例化WebClient对象
            WebClient wclient = new WebClient();
            //设置WebClient的基URI
            wclient.BaseAddress = textBox5.Text;//如:http://www.baidu.com/
            wclient.Encoding = Encoding.UTF8;//指定下载字符串的编码方式
            //为WebClient类对象添加标头
            wclient.Headers.Add("Content-Type","application/x-www-form-urlencoded");
            //使用OpenRead方法获取指定网站的数据,并保存到Stream流中
            Stream stream = wclient.OpenRead(textBox5.Text);
            //使用流Stream声明一个流读取变量sreader
            StreamReader sreader = new StreamReader(stream);
            string str = string.Empty;
            //循环读取从指定网站获得的数据
            while ((str = sreader.ReadLine()) != null)
            {
                richTextBox1.Text += str + "\n";
            }
            //调用WebClient对象的DownloadFile方法将指定网站的内容保存到文件中
            wclient.DownloadFile(textBox5.Text,DateTime.Now.ToFileTime()+".txt");
            MessageBox.Show("保存到文件成功");
        }
         /// <summary>
        /// 调用WebRequest和WebResponse类中的属性、方法获取指定网站的网页请求信息和网页内容
        /// 显示在richTextBox中
        /// </summary>
        private void button3_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = string.Empty;
            //实例化一个WebRequest对象
            WebRequest webrequest = WebRequest.Create(textBox5.Text);//http://www.baidu.com/
            //设置用于对Internet资源请求进行身份验证的网络凭据
            webrequest.Credentials = CredentialCache.DefaultCredentials;
            //调用WebRequest对象的各种属性获取WebRequest请求的相关信息
            richTextBox1.Text = "请求数据的内容长度" + webrequest.ContentLength;
            richTextBox1.Text += "\n该请求的协议方法:" + webrequest.Method;
            richTextBox1.Text += "\n访问Internet的网络代理:"+webrequest.Proxy;
            richTextBox1.Text += "\n 与该请求关联的internet URI:" +webrequest.RequestUri;
            richTextBox1.Text += "\n 超时时间:"+webrequest.Timeout;
            //调用WebRequest对象的GetResponse方法实例化一个WebResponse对象
            WebResponse webresponse = webrequest.GetResponse();
            //获取WebResponse响应的Internet资源的URI
            richTextBox1.Text += "\n 响应该请求的Internet URI:" + webresponse.ResponseUri;
            //调用WebResponse 对象的GetResponseStream方法返回数据流
            Stream stream = webresponse.GetResponseStream();
            //使用创建的Stream对象创建一个StreamReader流读取对象
            StreamReader sreader = new StreamReader(stream);
            richTextBox1.Text += "\n"+sreader.ReadToEnd();
            sreader.Close();
            stream.Close();
            webresponse.Close();
        }
         /// <summary>
        /// 连接远程主机并获得其主要内容
        /// </summary>
        private static Socket ConnectSocket(string server, int port)
        {
            Socket socket = null;//实例化Socket对象,并初始化为空
            IPHostEntry iphostentry = null;//实例化IPHostEntry,并初始化为空
            iphostentry = Dns.GetHostEntry(server);//获得主机信息
            foreach (IPAddress address in iphostentry.AddressList)
            {
                //使用指定的IP地址和端口号实例化IPEndPoint对象
                IPEndPoint IPEPoint = new IPEndPoint(address,port);
                //使用Socket的构造函数实例化一个Socket对象,以便用来连接远程主机
                Socket newSocket = new Socket(IPEPoint.AddressFamily,SocketType.Stream,ProtocolType.Tcp);
                newSocket.Connect(IPEPoint);//调用
                if (newSocket.Connected)
                {
                    socket = newSocket;
                    break;
                }
                else { continue; }
            }
            return socket;
        }
        private static string SocketSendReceive(string server, int port)
        {
            string request = "GET/HTTP/1.1\n主机:"+server+"\n连接:关闭\n";
            Byte[] btSend = Encoding.ASCII.GetBytes(request);
            Byte[] btReceived = new Byte[256];
            //调用自定义方法ConnectSocket,使用指定的服务器名和端口号实例化一个Socket对象
            Socket socket = ConnectSocket(server,port);
            if (socket == null)
            { 
                return ("连接失败!");
            }
            //将请求发送到连接的服务器
            socket.Send(btSend,btSend.Length,0);
            int intContent = 0;
            string strContent = server + "上的默认页面内容:\n";
            do
            {
                //从绑定的Socket接收数据
                intContent=socket.Receive(btReceived,btReceived.Length,0);
                strContent+=Encoding.ASCII.GetString(btReceived,0,intContent);
            }
            while(intContent>0);
            return strContent;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string server = textBox1.Text;//指定主机名
            int port = Convert.ToInt32(textBox2.Text);//指定端口号
            //调用自定义方法SocketSendReceive获取指定主机名的主页内容
            string strContent = SocketSendReceive(server,port);
            MessageBox.Show(strContent);
        }

 

        private void button5_Click(object sender, EventArgs e)
        {
            //实例化一个TcpListener对象,并初始化为空
            TcpListener tcplistener = null;
            //实例化一个IPAddress对象,用来表示网络IP地址 如:192.168.1.96
            IPAddress ipaddress = IPAddress.Parse(textBox1.Text);
            //定义一个int类型变量,用来存储端口号 如:8080
            int port = Convert.ToInt32(textBox2.Text);
            tcplistener = new TcpListener(ipaddress,port);//初始化TcpListener对象
            tcplistener.Start();//开始TcpListener侦听
            richTextBox1.Text = "等待连接...\n";
            TcpClient tcpclient = null;//实例化一个TcpClient对象,并赋值为空
            if (tcplistener.Pending())
            {
                tcpclient = tcplistener.AcceptTcpClient();//使用TcpClient的构造函数初始化TcpClient对象
            }
            else
                tcpclient = new TcpClient(textBox1.Text, port);//使用TcpClient的构造函数初始化TcpClient对象
            richTextBox1.Text += "连接成功!\n";
            tcpclient.Close();
            tcplistener.Stop();
        }

 

posted on 2012-08-23 11:47  悟生慧  阅读(717)  评论(0编辑  收藏  举报

导航