C#获取本地IP地址和MAC地址使用websocket 向服务器发起在线状态注册
时间: 2023-06-20 21:05:31 浏览: 196
要获取本地IP地址和MAC地址,您可以使用C#的System.Net.NetworkInformation命名空间中的NetworkInterface类。以下是一个示例代码:
```
using System.Net.NetworkInformation;
// 获取本地IP地址
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
IPInterfaceProperties ipProps = nic.GetIPProperties();
foreach (var ip in ipProps.UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
string ipAddress = ip.Address.ToString();
// 在此处使用WebSocket向服务器发送在线状态注册
}
}
}
}
// 获取本地MAC地址
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
PhysicalAddress mac = nic.GetPhysicalAddress();
string macAddress = BitConverter.ToString(mac.GetAddressBytes());
// 在此处使用WebSocket向服务器发送在线状态注册
}
}
```
要使用WebSocket向服务器发送在线状态注册,您需要使用C#中的WebSocket类,它位于System.Net.WebSockets命名空间中。以下是一个示例代码:
```
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
public static async Task SendWebSocketMessage(string message)
{
using (ClientWebSocket ws = new ClientWebSocket())
{
await ws.ConnectAsync(new Uri("ws://your-server-url"), CancellationToken.None);
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
ArraySegment<byte> messageSegment = new ArraySegment<byte>(messageBytes);
await ws.SendAsync(messageSegment, WebSocketMessageType.Text, true, CancellationToken.None);
}
}
```
将上述代码与获取本地IP地址和MAC地址的代码结合起来,您可以编写一个方法来向服务器发送在线状态注册:
```
public static async Task RegisterOnlineStatus()
{
// 获取本地IP地址
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
IPInterfaceProperties ipProps = nic.GetIPProperties();
foreach (var ip in ipProps.UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
string ipAddress = ip.Address.ToString();
// 向服务器发送在线状态注册
string message = $"{{\"type\": \"register\", \"ip\": \"{ipAddress}\"}}";
await SendWebSocketMessage(message);
}
}
}
}
// 获取本地MAC地址
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
PhysicalAddress mac = nic.GetPhysicalAddress();
string macAddress = BitConverter.ToString(mac.GetAddressBytes());
// 向服务器发送在线状态注册
string message = $"{{\"type\": \"register\", \"mac\": \"{macAddress}\"}}";
await SendWebSocketMessage(message);
}
}
}
```
请注意,此示例代码仅供参考,并且需要根据您的实际情况进行修改。例如,您需要替换“your-server-url”为您的服务器URL。
阅读全文