473,320 Members | 1,831 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,320 developers and data experts.

Extended UdpClient Class that adds WOL (Wake On Lan) Function

!NoItAll
297 100+
I have some windows software that manages multiple Linux boxes.
I wanted to add the ability to power up any of those boxes using WOL (Wake On Lan) so I wrote this UdpClient extension that adds an overloaded WakeFunction (see intellisense).
This code was translated (and simplified) from some existing C# examples found in various places.

Expand|Select|Wrap|Line Numbers
  1. Imports System.Net.Sockets
  2.  
  3. ''' <summary>
  4. ''' An extended UdpClient Class with WOL WakeFunction
  5. ''' </summary>
  6. Public Class WOLClass
  7.     Inherits UdpClient
  8.  
  9.     Public Sub New() : End Sub
  10.  
  11.     Public Sub New(IPAddress As String, NetMask As String)
  12.         Me.IPAddress = IPAddress
  13.         Me.NetMask = NetMask
  14.     End Sub
  15.  
  16.     Private Sub SetClientToBroadcastMode()
  17.         If Me.Active Then
  18.             Me.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, False)
  19.         End If
  20.     End Sub
  21.  
  22.     Public Property IPAddress As New String(String.Empty)
  23.  
  24.     Public Property NetMask As New String(String.Empty)
  25.  
  26.     ''' <summary>
  27.     ''' Send a magic packet to the entire subnet based on IP and NetMask properties to the MAC Address and Port
  28.     ''' </summary>
  29.     ''' <param name="MACAddress">The MAC Address of the machine to waken</param>
  30.     ''' <param name="Port">Remove port on destination system (default = 9)</param>
  31.     Public Function WakeFunction(MACAddress As String, Optional Port As Long = 9L) As Boolean
  32.         If Me.IPAddress.Length <> 0 AndAlso Me.NetMask.Length <> 0 Then
  33.             Return WakeFunction(Me.IPAddress, Me.NetMask, MACAddress, Port)
  34.         Else
  35.             Throw New Exception("IPAddress and NetMASK properties must be set before calling this overload")
  36.         End If
  37.     End Function
  38.  
  39.     ''' <summary>
  40.     ''' Sends a magic packet to the entire subnet based on IP and NetMask with the target set to the MAC Address
  41.     ''' </summary>
  42.     ''' <param name="IPAddress">The IP Address to which the Magic Packet is directed (can be a broadcast address)</param>
  43.     ''' <param name="NetMask">The Network Mask of the subnet</param>
  44.     ''' <param name="MacAddress">The targets MAC address as xx:xx:xx:xx:xx</param>
  45.     ''' <param name="Port">Remote port on destination system (default = 9)</param>
  46.     ''' 
  47.     Public Function WakeFunction(IPAddress As String, NetMask As String, MacAddress As String, Optional Port As Long = 9L) As Boolean
  48.  
  49.         Dim BrdAddress As Net.IPAddress = GetBroadcastAddress(Net.IPAddress.Parse(IPAddress).ToString, NetMask)
  50.         Dim Counter As Integer = 0
  51.         Dim bytes(1023) As Byte
  52.  
  53.         Using client As New WOLClass
  54.  
  55.             client.Connect(BrdAddress, Port)
  56.  
  57.             client.SetClientToBroadcastMode()
  58.  
  59.             For I As Integer = 0 To 5
  60.                 Counter = I
  61.                 bytes(Counter) = &HFF
  62.             Next
  63.  
  64.             Dim MacPieces As String() = MacAddress.Split({":"}, StringSplitOptions.RemoveEmptyEntries)
  65.  
  66.             For I As Integer = 0 To 15
  67.                 For J As Integer = 0 To 5
  68.                     Counter += 1
  69.                     bytes(Counter) = Byte.Parse(MacPieces(J), Globalization.NumberStyles.HexNumber)
  70.                 Next
  71.             Next
  72.  
  73.             Try
  74.                 client.Send(bytes, 1024I)
  75.                 Return True
  76.             Catch ex As Exception
  77.                 Throw New Exception(ex.Message)
  78.             End Try
  79.         End Using
  80.  
  81.     End Function
  82.  
  83.     ''' <summary>
  84.     ''' Returns the subnets broadcast address based on the provided IP Address and Subnet Mask
  85.     ''' </summary>
  86.     ''' <param name="IPAddress">Any IP in the subnet (can even be the current broadcast address)</param>
  87.     ''' <param name="NetMask">The NetMask of the the subnet</param>
  88.     ''' <returns></returns>
  89.     Private Function GetBroadcastAddress(IPAddress As String, NetMask As String) As Net.IPAddress
  90.  
  91.         Dim ThisAddress As Net.IPAddress = Net.IPAddress.Parse(IPAddress)
  92.         Dim ThisMask As Net.IPAddress = Net.IPAddress.Parse(NetMask)
  93.  
  94.         Dim IPPieces As String() = IPAddress.Split({"."}, StringSplitOptions.RemoveEmptyEntries)
  95.         Dim MaskPieces As String() = NetMask.Split({"."}, StringSplitOptions.RemoveEmptyEntries)
  96.  
  97.         Dim IPBytes As Byte() = ThisAddress.GetAddressBytes
  98.         Dim MaskBytes As Byte() = ThisMask.GetAddressBytes
  99.         Dim BroadcastAddress(3) As Byte
  100.  
  101.         For I As Integer = 0 To (IPBytes.Length - 1)
  102.             BroadcastAddress(I) = CByte((IPBytes(I) Or (MaskBytes(I) Xor 255)))
  103.         Next
  104.  
  105.         Return New Net.IPAddress(BroadcastAddress)
  106.  
  107.     End Function
  108. End Class
  109.  
Example Usage

Expand|Select|Wrap|Line Numbers
  1.         Using wc As New WOLClass("192.168.1.178", "255.255.255.0")
  2.             If wc.WakeFunction("ac:1f:6b:20:11:30") Then
  3.                 MsgBox("Magic Packet Sent", MsgBoxStyle.OkOnly Or MsgBoxStyle.Information)
  4.             End If
  5.         End Using
  6.  
Jul 29 '18 #1
0 4690

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Fernando Rodriguez | last post by:
Hi, I need to traverse the methods defined in a class and its superclasses. This is the code I'm using: # An instance of class B should be able to check all the methods defined in B #and A,...
1
by: QH Hong | last post by:
Hi, I have several classes and several members. class c1, c2, c3,... member of class c1 is m11, m12,... member of class c2 is m21, m22,... Each member takes one argument (double type) and...
2
by: Bj?rn Toft Madsen | last post by:
Hi all, The network library I use communicates with my app using a callback function. This callback function is called with the type of message, a void pointer to he actual message and a user...
3
by: Firstname Lastname | last post by:
In a function call, for example function(Class(), &Class::memfunc), my compiler cannot match the 2nd argument when: (1) Class is a template parameter, and (2) the base class of Class defines...
6
by: hazz | last post by:
I have a class/constructor hiearchy that functions correctly as illustrated below (thanks to Ken Kolda's earlier newsgroup assistance.) If a client instantiates object D, eg. D m_D = new...
9
by: Steve | last post by:
Hello -- I've been struggling with this problem for over a day now. I'd like to know (without passing parameters) which class, and preferably, which method of that class has called my function....
17
by: Jef Driesen | last post by:
Suppose I have a datastructure (actually it's a graph) with one template parameter (the property P for each edge and vertex): struct graph<P>; struct vertex<P>; struct edge<P>; I also have...
0
by: mongolian | last post by:
Hello, I am trying to execute an Extended Stored Procedure in a User Defined Function I wrote. It really is quite simple but I get an error saying "Only functions and extended stored procedures...
9
by: divya_rathore_ | last post by:
Why doesn't the following code work for a project? How else can I assign the 'class' keyword a value from outside (not embedded within the asp.net code, say as in: class=class_red)? //some C#...
1
by: PengYu.UT | last post by:
Hi, Are there any walkaround to enable functions in the derived class with the same function name but different return type? In the following example, D1 and D2 are B's derived class. I want...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.