Udp接收和发送


目的:
    某现场设备厂家通过snmp协议发送告警到网管侧设备上,网管snmp采集程序接收不到告警,通过抓包命令能看到网卡上有告警,snmp协议版本为V2.
    1)从网卡上抓包日志中读取二进制内容发送到某机器端口;
    2)通过Udp接收程序从机器端口接收告警;

接收端代码
   
  1. package com.udp;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.FileWriter;
  5. import java.io.IOException;
  6. import java.net.DatagramPacket;
  7. import java.net.DatagramSocket;
  8. import java.text.SimpleDateFormat;
  9. import java.util.Date;
  10. /**
  11. * UDP接收
  12. *
  13. * 可用下面方式运行到Unxi/Linux环境
  14. * a)程序目录情况
  15. * udptest
  16. * |--start.sh
  17. * |--udpreceive.jar
  18. * b)程序启停
  19. * 启动 ./start.sh
  20. * 停止 ps -ef | grep "program.name=UdpReceiver"|grep -v grep|awk '{print $2}'|xargs -i kill -9 {}
  21. * c)脚本start.sh内容如下
  22. #!/bin/sh
  23. JARS="./udpreceive.jar"
  24. export JARS
  25. lintenPort=1622
  26. nohup java -Dprogram.name=UdpReceiver -Dfile.encoding=GBK -cp $JARS com.boco.util.UdpReceiver $lintenPort &
  27. *
  28. * @author DAL.feng
  29. *
  30. */
  31. public class UdpReceiver {
  32. public static final int DEFAULT_LINSTEN_PORT = 1622;
  33. private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  34. private static String home = "";
  35. public static void main(String[] args) {
  36. System.out.println("UdpReceiver is start ...");
  37. receive(args);
  38. System.out.println("UdpReceiver is end!");
  39. }
  40. private static void receive(String[] args) {
  41. int linstenPort = init(args);
  42. System.out.println("linstening port : " + linstenPort);
  43. try {
  44. DatagramSocket udp = new DatagramSocket(linstenPort);
  45. udp.setSoTimeout(10);
  46. boolean isRun = true;
  47. long count = 1;
  48. while(isRun) {
  49. work(udp, count);
  50. count ++;
  51. }
  52. } catch (Exception e) {
  53. // TODO Auto-generated catch block
  54. e.printStackTrace();
  55. }
  56. }
  57. /**
  58. * 启动参数第一个是udp接收的监听端口
  59. * @param args
  60. * @return
  61. */
  62. private static int init(String[] args) {
  63. if(args == null || args.length < 1) {
  64. return DEFAULT_LINSTEN_PORT;
  65. }
  66. return Integer.parseInt(args[0].trim());
  67. }
  68. /**
  69. * 循环内的一次执行动作;
  70. * @param udp
  71. * @param count 动作执行次数
  72. */
  73. private static void work(DatagramSocket udp, long count) {
  74. try {
  75. DatagramPacket packet = receive0(udp);
  76. if(packet == null) {
  77. if(count % 6 == 1) {
  78. System.out.println(sdf.format(new Date()) + " --- no data");
  79. }
  80. Thread.sleep(1000);
  81. } else {
  82. byte[] receiveData = packet.getData();
  83. int dataLength = packet.getLength();
  84. String result = new String(receiveData, 0, dataLength);
  85. result = result.trim();
  86. System.out.println("receive length:" + packet.getLength());
  87. if(result.length() > 0) {
  88. System.out.println("receive data:" + result);
  89. }
  90. saveFile(receiveData, dataLength);
  91. packet = null;
  92. }
  93. } catch (Exception e) {
  94. // TODO Auto-generated catch block
  95. e.printStackTrace();
  96. }
  97. }
  98. /**
  99. * 从监听端口读取数据,有超时设置,默认10ms,如果无数据则返回null
  100. * @param udp
  101. * @return
  102. */
  103. private static DatagramPacket receive0(DatagramSocket udp) {
  104. byte[] buf = new byte[10240];
  105. DatagramPacket packet = new DatagramPacket(buf, buf.length);
  106. try {
  107. udp.receive(packet);
  108. } catch (Exception e) {
  109. // e.printStackTrace();
  110. packet = null;
  111. }
  112. return packet;
  113. }
  114. private static void saveFile(byte[] result, int length) {
  115. String filepath = getHome() + System.currentTimeMillis() + ".data";
  116. try {
  117. FileOutputStream f = new FileOutputStream(filepath);
  118. f.write(result, 0, length);
  119. f.flush();
  120. System.out.println("save file: " + filepath);
  121. f.close();
  122. } catch (Exception e) {
  123. // TODO Auto-generated catch block
  124. e.printStackTrace();
  125. }
  126. }
  127. private static String getHome() {
  128. if(home == null || "".equals(home)) {
  129. File f = new File("");
  130. String home0 = f.getAbsolutePath();
  131. System.out.println(home0);
  132. home = home0.endsWith("/") ? home0 : home0+"/";
  133. }
  134. return home;
  135. }
  136. }

从文件读取二进制内容发送到Udp端口
   
  1. package com.udp;
  2. import java.io.FileInputStream;
  3. import java.net.DatagramPacket;
  4. import java.net.DatagramSocket;
  5. import java.net.InetAddress;
  6. import junit.framework.TestCase;
  7. public class UdpLiteTest extends TestCase {
  8. protected void setUp() throws Exception {
  9. super.setUp();
  10. }
  11. public void testSendUdpLite() {
  12. String targetHost = "10.10.1.162";
  13. // String targetHost = "127.0.0.1";
  14. int targetPort = 1625;
  15. try {
  16. // 初始化udp,采用随机端口
  17. DatagramSocket udp = new DatagramSocket();
  18. // 初始化数据包,里面包含了数据byte[],目的地址,和目的端口,数据发送到哪,完全由数据包中目的地址和端口决定
  19. DatagramPacket data = new DatagramPacket(new byte[0], 0, InetAddress.getByName(targetHost), targetPort);
  20. // 读数据
  21. data.setData(readSnmpData());
  22. // 读心跳
  23. // data.setData(readSnmpHeart());
  24. // data.setData(readSnmpClient());
  25. // 读其他模拟程序发的snmp内容,这个是一个完整的snmp样例
  26. data.setData(readSnmpRealLong());
  27. udp.send(data);
  28. System.out.println("send finish");
  29. } catch (Exception e) {
  30. // TODO Auto-generated catch block
  31. e.printStackTrace();
  32. }
  33. }
  34. private byte[] readSnmpData() {
  35. String snoopResultPath = "d:/03-Run/snmp/1009-1";
  36. // int snmpLength = 2783;
  37. int snmpLength = 1472;
  38. int start = 0x850 + 10;
  39. return readSnmp0(snoopResultPath, snmpLength, start);
  40. }
  41. private byte[] readSnmpHeart() {
  42. String snoopResultPath = "d:/03-Run/snmp/1009-1";
  43. int snmpLength = 187;
  44. int start = 0x650 + 10;
  45. return readSnmp0(snoopResultPath, snmpLength, start);
  46. }
  47. private byte[] readSnmpClient() {
  48. String snoopResultPath = "d:/03-Run/snmp/soo7";
  49. int snmpLength = 1176;
  50. int start = 0x50 + 2;
  51. return readSnmp0(snoopResultPath, snmpLength, start);
  52. }
  53. private byte[] readSnmpRealLong() {
  54. String snoopResultPath = "d:/03-Run/snmp/1622-2.pcap";
  55. int snmpLength = 3041;
  56. int start = 0x50 + 2;
  57. return readSnmp0(snoopResultPath, snmpLength, start);
  58. }
  59. private byte[] readSnmp0(String snoopFilepath, int readLength, int startIndex) {
  60. String snoopResultPath = snoopFilepath;
  61. int snmpLength = readLength;
  62. int start = startIndex;
  63. byte[] content = new byte[snmpLength];
  64. try {
  65. FileInputStream is = new FileInputStream(snoopResultPath);
  66. // 先将起始位置之前的字节给去掉
  67. is.skip(start);
  68. is.read(content, 0, snmpLength);
  69. System.out.println("------ content:" + new String(content));
  70. // content = "ssss".getBytes();
  71. is.close();
  72. } catch (Exception e) {
  73. // TODO Auto-generated catch block
  74. e.printStackTrace();
  75. }
  76. return content;
  77. }
  78. }








附件列表

 

转载于:https://my.oschina.net/u/1997676/blog/402380

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值