Last active
June 26, 2018 09:24
-
-
Save tiandiduwuxiaoxiao/0ce769d2a8ca1045acaa281f6f84d69a to your computer and use it in GitHub Desktop.
socket with c#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
``` | |
using System; | |
using System.Net; | |
using System.Net.Sockets; | |
using System.Runtime.InteropServices; | |
namespace socket | |
{ | |
class RawSocket | |
{ | |
Socket socket; | |
int count = 10; | |
bool error_occurred; | |
public bool KeepRunning; | |
byte[] receive_buf_bytes; | |
static int len_recive_buf; | |
const int SIO_RCVALL = unchecked((int)0x98000001); | |
public RawSocket() | |
{ | |
KeepRunning = true; | |
len_recive_buf = 4096; | |
error_occurred = false; | |
receive_buf_bytes = new byte[len_recive_buf]; | |
InitSocket("ip"); | |
} | |
public void Run() | |
{ | |
IAsyncResult res = socket.BeginReceive(receive_buf_bytes, 0, len_recive_buf, SocketFlags.None, new AsyncCallback(CallReceive), this); | |
} | |
private void InitSocket(string IP) | |
{ | |
socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP); | |
socket.Blocking = false; | |
socket.Bind(new IPEndPoint(IPAddress.Parse(IP), 0)); | |
if (SetSocketOption() == false) | |
error_occurred = true; | |
} | |
private bool SetSocketOption() | |
{ | |
bool ret_value = true; | |
try | |
{ | |
byte[] OUT = new byte[4]; | |
byte[] IN = new byte[4] { 1, 0, 0, 0 }; | |
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1); | |
int ret_code = socket.IOControl(SIO_RCVALL, IN, OUT); | |
ret_code = OUT[0] + OUT[1] + OUT[2] + OUT[3]; | |
if (ret_code != 0) | |
ret_value = false; | |
} | |
catch (SocketException) | |
{ | |
ret_value = false; | |
} | |
return ret_value; | |
} | |
private void CallReceive(IAsyncResult res) | |
{ | |
int received_bytes; | |
received_bytes = socket.EndReceive(res); | |
Receive(receive_buf_bytes, received_bytes); | |
if (KeepRunning) | |
{ | |
Run(); | |
} | |
} | |
private void Receive(byte[] buf, int len) | |
{ | |
var res = buf; | |
Console.WriteLine(buf); | |
count--; | |
if(count == 0) | |
{ | |
ShutDown(); | |
} | |
} | |
public void ShutDown() | |
{ | |
if (socket != null) | |
{ | |
socket.Shutdown(SocketShutdown.Both); | |
socket.Close(); | |
} | |
} | |
} | |
[StructLayout(LayoutKind.Explicit)] | |
public struct IPHeader | |
{ | |
} | |
} | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment