Showing posts with label 【Visual Studio Visual Csharp】IP Address. Show all posts
Showing posts with label 【Visual Studio Visual Csharp】IP Address. Show all posts

Friday, May 21, 2021

【Visual Studio Visual Csharp】IP Address

 using System;

using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net; // need namespace System.Net; using System.IO; // need namespace System.IO; using System.Net.Sockets; // need namespace System.Net.Sockets; namespace Ip_addresses { public partial class Form1 : Form { public Form1() { InitializeComponent(); label2.Text = GetPublicIP().ToString(); localIPAddress(); } public void localIPAddress() { //To get the local IP address string sHostName = Dns.GetHostName(); IPHostEntry ipE = Dns.GetHostByName(sHostName); IPAddress[] IpA = ipE.AddressList; for (int i = 0; i < IpA.Length; i++) { listBox1.Items.Add(IpA[i].ToString()); } } private IPAddress LocalIPAddress1() { if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) { return null; } IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName()); return host.AddressList .FirstOrDefault(Ip_addresses => Ip_addresses.AddressFamily == AddressFamily.InterNetwork); } public string GetPublicIP() { String direction = ""; WebRequest request = WebRequest.Create("http://checkip.dyndns.org/"); using (WebResponse response = request.GetResponse()) using (StreamReader stream = new StreamReader(response.GetResponseStream())) { direction = stream.ReadToEnd(); } //Search for the ip in the html int first = direction.IndexOf("Address: ") + 9; int last = direction.LastIndexOf("</body>"); direction = direction.Substring(first, last - first); return direction; } public string LocalIPAddress() { IPHostEntry host; string localIP = ""; host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { localIP = ip.ToString(); break; } } return localIP; } private void Form1_Load(object sender, EventArgs e) { } } }