ÆÊÎö Linux linkwatch Àú³ÌµÄ×÷ÓúÍÔËÐлúÖÆ
Linux linkwatch Àú³ÌµÄ×÷ÓúÍÔËÐлúÖÆ
ÔÚLinuxϵͳÖУ¬linkwatch Àú³ÌÊÇÒ»¸öÈÏÕæ¼à²âÍøÂçÅþÁ¬×´Ì¬µÄÊØ»¤Àú³Ì£¬ÆäÖ÷Òª×÷ÓÃÊÇÔÚÍøÂç½Ó¿Ú״̬¸Ä±äʱ£¬¼´ÅþÁ¬»ò¶Ï¿ªÊ±¾ÙÐÐÏìÓ¦µÄ²Ù×÷¡£linkwatch Àú³Ìͨ¹ý¼àÌýÍøÂç½Ó¿Ú״̬ת±äÀ´ÊµÏÖ¶ÔÍøÂçÅþÁ¬µÄʵʱ¼à¿Ø£¬²¢Æ¾Ö¤×´Ì¬×ª±ä×ö³öÏìÓ¦µÄ´¦Öóͷ£¡£
linkwatch Àú³ÌµÄ×÷Óãº
¼à²âÍøÂçÅþÁ¬×´Ì¬£ºlinkwatch Àú³Ì»áÒ»Á¬¼àÌýÍøÂç½Ó¿ÚµÄ״̬ת±ä£¬°üÀ¨ÍøÂçÅþÁ¬µÄ½¨Éè¡¢¶Ï¿ªÒÔ¼°ÖØÐÂÅþÁ¬µÈÇéÐΡ£
´¦Öóͷ£ÍøÂçÅþÁ¬ÊÂÎñ£ºÔÚÎüÊÕµ½ÍøÂç½Ó¿Ú״̬ת±äµÄ֪ͨºó£¬linkwatch Àú³Ì»áƾ֤ÏêϸµÄÊÂÎñ¾ÙÐÐÏìÓ¦µÄ´¦Öóͷ££¬ºÃ±ÈÖØÐÂÉèÖÃÍøÂç²ÎÊý¡¢´¥·¢ÆäËûЧÀÍ»ò¾ç±¾µÄÖ´Ðеȡ£
ÌṩʵʱÍøÂç״̬ÐÅÏ¢£ºlinkwatch Àú³Ì¿ÉÒÔÏòϵͳÖÎÀíÔ±ÌṩʵʱµÄÍøÂç״̬ÐÅÏ¢£¬×ÊÖúÖÎÀíԱʵʱÏàʶÍøÂçÅþÁ¬µÄÇéÐβ¢ÊµÊ±×ö³öµ÷½â¡£
linkwatch Àú³ÌµÄÔËÐлúÖÆ£º
linkwatch Àú³Ìͨ¹ý¼àÌýÄÚºËµÄ Netlink socket ʵÏÖ¶ÔÍøÂç½Ó¿Ú״̬µÄʵʱ¼à¿Ø¡£µ±ÍøÂç½Ó¿Ú״̬±¬·¢×ª±äʱ£¬Äں˻ᷢËÍÏìÓ¦µÄ֪ͨÐÂÎŵ½ linkwatch Àú³Ì£¬Í¨Öª linkwatch Àú³ÌÓйØÅþÁ¬×ª±äµÄÏêϸÐÅÏ¢¡£linkwatch Àú³ÌÎüÊÕµ½Í¨Öªºó£¬±ãƾ֤ÏêϸµÄÊÂÎñÀàÐÍÖ´ÐÐÏìÓ¦µÄ²Ù×÷¡£
ÏÂÃæÊÇÒ»¸ö¼òÆÓµÄʾÀý´úÂ룬չʾÁËÔõÑùʹÓà Python ±àдһ¸öÄ£Äâ linkwatch Àú³ÌµÄ³ÌÐò£¬ÊµÏÖ¶ÔÍøÂç½Ó¿Ú״̬µÄ¼à¿Ø²¢Êä³ö״̬ÐÅÏ¢£º
import socket import struct # ½¨Éè Netlink socket£¬ÓÃÓÚÎüÊÕÄں˵Ä֪ͨ sock = socket.socket(socket.AF_NETLINK, socket.SOCK_RAW, socket.NETLINK_ROUTE) sock.bind((0, 0)) # ¼àÌýÍøÂç½Ó¿Ú״̬ת±ä while True: data = sock.recv(65535) _, _, _, _, msg_type, flags, seq, pid = struct.unpack("=IHHHBBII", data[:20]) if msg_type == 16: # RTM_NEWLINK print("Network interface state changed: connected") elif msg_type == 17: # RTM_DELLINK print("Network interface state changed: disconnected")
µÇ¼ºó¸´ÖÆ
´Ë´úÂëʾÀýÄ£ÄâÁË linkwatch Àú³ÌµÄ»ù±¾¹¦Ð§£¬Í¨¹ý¼àÌý Netlink socket ÎüÊÕµ½µÄÐÂÎÅ£¬ÅжÏÍøÂç½Ó¿Ú״̬µÄת±ä²¢Êä³öÏìÓ¦µÄÐÅÏ¢¡£ÏÖʵ linkwatch Àú³ÌµÄʵÏÖ»áÔ½·¢ÖØ´ó£¬Éæ¼°µ½¸ü¶àµÄÍøÂç״̬´¦Öóͷ£ºÍÖÎÀí»úÖÆ¡£
×ܶøÑÔÖ®£¬Linux linkwatch Àú³ÌÊÇÒ»¸öÖ÷ÒªµÄÍøÂçÅþÁ¬¼à¿Ø¹¤¾ß£¬Í¨¹ýʵʱ¼àÌýÍøÂç½Ó¿Ú״̬ת±ä£¬×ÊÖúϵͳÖÎÀíÔ±×·×ÙÍøÂçÅþÁ¬ÇéÐΣ¬°ü¹ÜÍøÂçµÄÕý³£ÔËÐС£
ÒÔÉϾÍÊÇÆÊÎö Linux linkwatch Àú³ÌµÄ×÷ÓúÍÔËÐлúÖƵÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡