sockets - Lua 原始套接字示例

标签 sockets network-programming lua

我很难在 Lua 中找到一些原始套接字的示例代码。理想情况下,它们应该看起来像在 Python 中所做的那样:

#create a raw socket
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
except socket.error , msg:
    print 'Socket could not be created. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

# tell kernel not to put in headers, since we are providing it, when using IPPROTO_RAW this is not necessary
# s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

# now start constructing the packet
packet = '';

source_ip = '192.168.1.101'
dest_ip = '127.0.0.1' # or socket.gethostbyname('www.google.com')

# ip header fields
ip_ihl = 5
ip_ver = 4
ip_tos = 0
ip_tot_len = 0  # kernel will fill the correct total length
ip_id = 54321   #Id of this packet
ip_frag_off = 0
ip_ttl = 255
ip_proto = socket.IPPROTO_TCP
ip_check = 0    # kernel will fill the correct checksum
ip_saddr = socket.inet_aton ( source_ip )   #Spoof the source ip address if you want to
ip_daddr = socket.inet_aton ( dest_ip )

ip_ihl_ver = (ip_ver << 4) + ip_ihl

# the ! in the pack format string means network order
ip_header = pack('!BBHHHBBH4s4s' , ip_ihl_ver, ip_tos, ip_tot_len, ip_id, ip_frag_off, ip_ttl, ip_proto, ip_check, ip_saddr, ip_daddr)

# tcp header fields
tcp_source = 1234   # source port
tcp_dest = 80   # destination port
tcp_seq = 454
tcp_ack_seq = 0
tcp_doff = 5    #4 bit field, size of tcp header, 5 * 4 = 20 bytes
#tcp flags
tcp_fin = 0
tcp_syn = 1
tcp_rst = 0
tcp_psh = 0
tcp_ack = 0
tcp_urg = 0
tcp_window = socket.htons (5840)    #   maximum allowed window size
tcp_check = 0
tcp_urg_ptr = 0

tcp_offset_res = (tcp_doff << 4) + 0
tcp_flags = tcp_fin + (tcp_syn << 1) + (tcp_rst << 2) + (tcp_psh <<3) + (tcp_ack << 4) + (tcp_urg << 5)

# the ! in the pack format string means network order
tcp_header = pack('!HHLLBBHHH' , tcp_source, tcp_dest, tcp_seq, tcp_ack_seq, tcp_offset_res, tcp_flags,  tcp_window, tcp_check, tcp_urg_ptr)

user_data = 'Hello, how are you'

如果你们有一些闲置或知道在哪里可以找到一些。我没有从我的谷歌搜索中看到太多。

谢谢,

最佳答案

LuaSocket 不是为此而生的。也许看看libpcaplibnet

关于sockets - Lua 原始套接字示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16904493/

相关文章:

Lua虚拟机寄存器大小

sqlite在打开连接后首先执行查询慢

c++ - getaddrinfo,我没有得到任何 canonname

.net - Azure Functions 在函数内调用 http post

c - 远程套接字上 select() 的行为已关闭(通过终止进程)

java - 简单的Java网络IO不适用于大数据

c - 如何获取客户端程序的本地 TCP 端口和 IP 地址?

java - 将数据从 C 服务器代码发送到 java 客户端代码

c - 如何获取网络设备统计信息?

python - 从 python 调用 torch7 ( Lua ) 函数?