首页 > 编程语言 >C# WakeOnLan 唤醒局域网内电脑

C# WakeOnLan 唤醒局域网内电脑

时间:2023-04-24 22:23:40浏览次数:27  
标签:macAddress unicastIPAddressInformation C# magicPacket WakeOnLan static byte 局域网 

首先需要开启被唤醒电脑的WOL功能

进入BIOS,寻找有关WOL相关项,我的电脑BIOS里面叫做network stack

打开网卡界面,选中网卡右键打开属性

 然后点击配置

 选择高级,启用唤醒幻数据包

 选择电源管理,勾选以下2个选项

 C#唤醒局域网内电脑代码

namespace WakeOnLan
{
    internal class Program
    {
        public static void Main()
        {
            WakeComputer("60-E3-2B-D0-79-D3","192.168.189.138");
            Thread.Sleep(1000);
            Console.WriteLine("ok");
            Console.ReadKey();
        }
        async static void WakeComputer(string mac,string ip)
        {
            await WOL.WakeOnLan(mac, ip);
        }
    }
    public static class WOL
    {
        public static async Task WakeOnLan(string macAddress,string ipAddress)
        {
            byte[] magicPacket = BuildMagicPacket(macAddress);
            foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces().Where((n) =>
                n.NetworkInterfaceType != NetworkInterfaceType.Loopback && n.OperationalStatus == OperationalStatus.Up))
            {
                IPInterfaceProperties iPInterfaceProperties = networkInterface.GetIPProperties();
                foreach (MulticastIPAddressInformation multicastIPAddressInformation in iPInterfaceProperties.MulticastAddresses)
                {
                    IPAddress multicastIpAddress = multicastIPAddressInformation.Address;
                    if (multicastIpAddress.ToString().StartsWith("ff02::1%", StringComparison.OrdinalIgnoreCase)) // Ipv6: All hosts on LAN (with zone index)
                    {
                        UnicastIPAddressInformation unicastIPAddressInformation = iPInterfaceProperties.UnicastAddresses.Where((u) =>
                            u.Address.AddressFamily == AddressFamily.InterNetworkV6 && !u.Address.IsIPv6LinkLocal).FirstOrDefault();
                        if (unicastIPAddressInformation != null)
                        {
                            await SendWakeOnLan(unicastIPAddressInformation.Address, multicastIpAddress, magicPacket);
                            break;
                        }
                    }
                    else if (multicastIpAddress.ToString().Equals(ipAddress)) // Ipv4: All hosts on LAN
                    {
                        UnicastIPAddressInformation unicastIPAddressInformation = iPInterfaceProperties.UnicastAddresses.Where((u) =>
                            u.Address.AddressFamily == AddressFamily.InterNetwork && !iPInterfaceProperties.GetIPv4Properties().IsAutomaticPrivateAddressingActive).FirstOrDefault();
                        if (unicastIPAddressInformation != null)
                        {
                            await SendWakeOnLan(unicastIPAddressInformation.Address, multicastIpAddress, magicPacket);
                            break;
                        }
                    }
                }
            }
        }
        static byte[] BuildMagicPacket(string macAddress) // MacAddress in any standard HEX format
        {
            macAddress = Regex.Replace(macAddress, "[: -]", "");
            byte[] macBytes = new byte[6];
            for (int i = 0; i < 6; i++)
            {
                macBytes[i] = Convert.ToByte(macAddress.Substring(i * 2, 2), 16);
            }
            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    for (int i = 0; i < 6; i++)  //First 6 times 0xff
                    {
                        bw.Write((byte)0xff);
                    }
                    for (int i = 0; i < 16; i++) // then 16 times MacAddress
                    {
                        bw.Write(macBytes);
                    }
                }
                return ms.ToArray(); // 102 bytes magic packet
            }
        }
        static async Task SendWakeOnLan(IPAddress localIpAddress, IPAddress multicastIpAddress, byte[] magicPacket)
        {
            using (UdpClient client = new UdpClient(new IPEndPoint(localIpAddress, 0)))
            {
                await client.SendAsync(magicPacket, magicPacket.Length, multicastIpAddress.ToString(), 9);
            }
        }
    }
}

  

 

标签:macAddress,unicastIPAddressInformation,C#,magicPacket,WakeOnLan,static,byte,局域网,
From: https://www.cnblogs.com/QJZY/p/17351153.html

相关文章

  • 电力系统潮流计算matlab仿真,计算结果自动保存到excel文件中
    1.算法仿真效果matlab2022a仿真结果如下:  2.算法涉及理论知识概要       在电力工程中,“潮流”还特指电网各处电压(包括幅值与相角)、有功功率、无功功率等的分布。潮流的分布是运行调度单位和维修部门所必须知道的事项。       而潮流计算,是指给定电网中一......
  • Navicat连接Oracle报错:ORA-28547...
    使用Navicat连接正常的oracle数据库时,提示 可能是因为Navicat本地的OCI版本与Oracle数据库版本不符造成的,可以下载对应的OCI版本在Navicat中使用。1.下载OCI搜索oracleinstantclient找到相关下载地址OracleInstantClientDownloads根据实际oracle数据库版本选择对应in......
  • 【ⓈSpring & Spring MVC】Spring核心接口InitializingBean与SmartInitializingSingle
    SmartInitializingSingletonSmartInitializingSingleton中只有一个接口afterSingletonsInstantiated(),其作用是在spring容器管理的所有单例对象(非懒加载对象)初始化完成之后调用的回调接口。InitializingBeanInitializingBean接口为bean提供了初始化方法的方式,它只包括afterProp......
  • [Week 18] 每日一题(C++,动态规划,线段树,数学)
    目录[Daimayuan]T1最长公共子序列(C++,DP,二分)输入格式输出格式数据范围输入样例输出样例解题思路[Daimayuan]T2喵喵序列(C++,序偶)题目描述输入格式输出格式样例输入样例输出样例说明数据范围双倍经验解题思路:[Daimayuan]T3漂亮数(C++,字符串)输入描述输出描述输入样例输出样例解题......
  • Numerical Approximation Chapter 6 Notes
    Weierstrasstheoremapproximation之间也有高低,所以我们在compactsubset里面会有bestapproximation.但是以polynomialinterpolation为例,随着不断选更多的Chebyshevinterpolationpoints,对应的插值多项式次数越来越高的同时也会在插值点以外的地方越来越靠近函数本身。这种情......
  • C++变量的大小
    #include<iostream>usingnamespacestd;intmain(){ cout<<"==========BASICVARIABLESSIZELIST=========="<<endl; cout<<"short:"<<sizeof(short)<<"bytes"<<endl; ......
  • [CMU 15-418] (Lecture4) Parallel Programming Basics
    本系列文章为CMU15-418/15-618:ParallelComputerArchitectureandProgramming,Fall2018课程学习笔记课程官网:CMU15-418/15-618:ParallelComputerArchitectureandProgramming参考文章:CMU15-418notes相关资源与介绍:CMU15-418/StanfordCS149:ParallelComput......
  • Serre算术教程Chapter 5笔记
    二次型的范畴论定义考虑这样一个范畴\(S_n\),由一些freeabeliangroupofrank\(n\)\(E\)组成Definitionoffreeabeliangroup一个有basis的abeliangroup.这里basis就是那个基的意思,everyelementcouldbeuniquelyexpressedasanlinearcombinationoffinitelyma......
  • 《c#高级编程》第2章C#2.0中的更改(二)——匿名类型
    一、概念C#中的匿名类型是一种特殊类型,可以在运行时动态创建一个对象,该对象可以包含多个属性,这些属性的名称和类型可以在创建时指定。相对于定义具体的类,匿名类型更加灵活和简洁。C#的匿名类型通常用于临时存储一组数据,这些数据可能来自不同的源头,或者只是需要在局部范围内使用......
  • vue2源码-十四、computed和watch的区别
    computed和watch的区别computed和watch的相同点。底层都会创建一个watcher(用法的区别:computed定义的属性可以在模板中使用,watch不能在视图中使用)computed默认不会执行只有取值的时候才会执行内部会维护一个dirty属性,来控制依赖的值是否发生变化。默认计算属性需要同......