python网络编程测试-broadcast
话说几天没上博客,总是觉的少点什么东西(因为抓了个小偷),今天来说说最近写的小测试吧,以后似乎大项目上改改就可以了
1 broadcast:(以下均使用IPv4 , no v6,当然更没v5)
广播对于路由来说是至关重要的,涉及的网络知识这里就不多介绍了,先看看code,看看Python中对于广播的处理
host:(接收广播包,并进行应答)
[python] def hostBroadcastRecv():
host = ''
print('input the port number for recieving broadcast data:')
port = sys.stdin.readline().rstrip()
s = socket.socket(socket.AF_INET , socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET , socket.SO_REUSEADDR , 1)
s.setsockopt(socket.SOL_SOCKET , socket.SO_BROADCAST , 1)
s.bind((host , int(port)))
while True:
try:
mess , addr = s.recvfrom(1024)
print('got data from broadcast')
s.sendto('got your broadcast' , addr)
except (KeyboardInterrupt , SystemExit):
print('terminate the procedure?')
flag = sys.stdin.readline().rstrip()
if(flag == 'yes') or (flag == 'y'):
sys.exit(1)
else:
continue
except:
traceback.print_exc()
def hostBroadcastRecv():
host = ''
print('input the port number for recieving broadcast data:')
port = sys.stdin.readline().rstrip()
s = socket.socket(socket.AF_INET , socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET , socket.SO_REUSEADDR , 1)
s.setsockopt(socket.SOL_SOCKET , socket.SO_BROADCAST , 1)
s.bind((host , int(port)))
while True:
try:
mess , addr = s.recvfrom(1024)
print('got data from broadcast')
s.sendto('got your broadcast' , addr)
except (KeyboardInterrupt , SystemExit):
print('terminate the procedure?')
flag = sys.stdin.readline().rstrip()
if(flag == 'yes') or (flag == 'y'):
sys.exit(1)
else:
continue
except:
traceback.print_exc()
client:(发出广播包)
[python]def sendBroadcastData():
print('input the data for sending...')
data = sys.stdin.readline().rstrip()
try:
dest = ('<broadcast>' , 5522)
s = socket.socket(socket.AF_INET , socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET , socket.SO_BROADCAST, 1)
s.sendto('testing...' , dest)
mess , addr = s.recvfrom(1024)
print(str(mess))
except (KeyboardInterrupt , SystemExit):
print('terminate the procedure?')
flag = sys.stdin.readline().rstrip()
if((flag == 'yes') or (flag == 'y')):
sys.exit(1)
else:
continue
except:
sys.exit(1)
def sendBroadcastData():
print('input the data for sending...')
data = sys.stdin.readline().rstrip()
try:
dest = ('<broadcast>' , 5522)
s = socket.socket(socket.AF_INET , socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET , socket.SO_BROADCAST, 1)
s.sendto('testing...' , dest)
mess , addr = s.recvfrom(1024)
print(str(mess))
except (KeyboardInterrupt , SystemExit):
print('terminate the procedure?')
flag = sys.stdin.readline().rstrip()
if((flag == 'yes') or (flag == 'y')):
sys.exit(1)
else:
continue
except:
sys.exit(1)
有些时候,我们要求应用具有单向传输的功能(这里所说的并非半双工,或者双工),那么通过Python中的shutdown可以达到我们的目的(是否有其他方法还不清楚,望牛人指点)
socket.shutdown(int) 函数用来说明怎样关闭socket switch(int):
case 0:禁止将来读
case 1:禁止将来写
case 2:禁止将来的读和写 (”将来“说明,该函数并不会对现在所处理的请求发生作用)
通常在以下情况下会使用这种办开放socket:
1 确保所有的已经写好的数据发出
2 捕获潜在的程序错误
3 程序中使用了fork()或多线程,并且像防止其他进程的某些操作。
4 立即关闭socket
摘自 FishinLab的专栏
补充:Web开发 , Python ,