void makeCall() { session.State = SessionState.Leg2Signaling; var _destIPAddress = IPUtil.ExtractIPAddress(legOutOptions[outboundAttempt - 1].DestIPAndPort); var _destNumberAndPrefix = legOutOptions[outboundAttempt - 1].DestNumber; //var _destPrefix = getPrefix(_destNumberAndPrefix); //var _destNumber = getDestNumber(_destNumberAndPrefix, _destPrefix.Length); var _customHeader = legOutOptions[outboundAttempt - 1].CustomHeader ?? string.Empty; if (session.Channel.MakeCall(session.ANI, _destNumberAndPrefix, _destIPAddress, isNotCallRoutingScript, _customHeader)) { if (isCallRoutingScript) { session.Channel.SendAcceptCall(Script.ScriptType.ToString()); session.Channel.WaitForEventIn(); } session.State = SessionState.Leg2Redirecting; if (session.Channel.RedirectMedia()) { session.State = SessionState.Leg2; if (isNotCallRoutingScript) { session.Channel.DestroyResources(); } setConnected(_destIPAddress); waitForCallEnd(); return; } throw new RbrException(RbrResult.IVR_MakeCallOut, "SessionScriptBase.makeCall", "ERROR: RedirectCall failed"); } throw new RbrException(RbrResult.IVR_MakeCallOut, "SessionScriptBase.makeCall", "ERROR: MakeCall Failed"); }
public void GetIPAddress_ArgumentNullException_Test() { byte[] data = null; IPAddress actual = IPUtil.GetIPAddress(data); Assert.AreEqual(actual, null); }
public void createServer() { LogUtil.instance.Log("-------开启创建读卡器服务-------"); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); const int port = 6547; //端口号 string host = IPUtil.GetLocalIpv4()[0]; //获取本机IP try { IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(host), port); //IPEndPoint类是对ip端口做了一层封装的 server.Bind(ipe); //向操作系统申请一个可用的ip地址和端口号用于通信 server.Listen(100); //设置最大的连接数 LogUtil.instance.Log("创建端口:" + port + " 等待读卡器客户端连接中..."); } catch (Exception e) { LogUtil.instance.Log("-------创建读卡器Socket失败-------"); throw e; } while (true) { createClienAcceptThread(server.Accept());//阻塞状态,等待连接,创建线程接收信息 } }
public void GetIPText_Exception_NulllReference_Test() { byte[] data = null; string actual = IPUtil.GetIPText(data); Assert.AreEqual(actual, string.Empty); }
public Cdr(string pCallId, string pOrigIP, string pPrefixIn, string pDestNumber, short pCustomerAcctId, int pCustomerRouteId) { cdrRow = new CDRRow(); cdrRow.Id = pCallId; cdrRow.Start = DateTime.Now; cdrRow.Date_logged = cdrRow.Start; cdrRow.Timok_date = TimokDate.Parse(cdrRow.Start); cdrRow.Duration = 0; cdrRow.Customer_duration = 0; cdrRow.Retail_duration = 0; cdrRow.Carrier_duration = 0; cdrRow.Ccode = 0; cdrRow.Local_number = pDestNumber; cdrRow.Carrier_route_id = 0; cdrRow.Customer_route_id = pCustomerRouteId; cdrRow.Price = (decimal)0.0; cdrRow.Cost = (decimal)0.0; cdrRow.Orig_IP_address = IPUtil.ToInt32(pOrigIP); OrigIP = IPUtil.ToString(cdrRow.Orig_IP_address); cdrRow.Term_end_point_id = 0; cdrRow.Customer_acct_id = pCustomerAcctId; cdrRow.Carrier_acct_id = 0; cdrRow.Disconnect_cause = 0; cdrRow.Mapped_disconnect_cause = 0; cdrRow.Rbr_result = (short)RbrResult.Unknown; cdrRow.Prefix_in = pPrefixIn; cdrRow.Prefix_out = string.Empty; cdrRow.DNIS = 0; cdrRow.ANI = 0; cdrRow.Serial_number = 0; cdrRow.Used_bonus_minutes = 0; cdrRow.Node_id = 0; }
internal static bool CheckIP(Player p) { if (!Server.Config.IPSpamCheck || IPUtil.IsLocal(p.IP)) { return(true); } DateTime blockedUntil, now = DateTime.UtcNow; lock (ipsLock) { IPThrottleEntry entry; if (!ips.TryGetValue(p.ip, out entry)) { entry = new IPThrottleEntry(); ips[p.ip] = entry; } blockedUntil = entry.BlockedUntil; if (blockedUntil < now) { if (!entry.AddSpamEntry(Server.Config.IPSpamCount, Server.Config.IPSpamInterval)) { entry.BlockedUntil = now.Add(Server.Config.IPSpamBlockTime); } return(true); } } // do this outside lock since we want to minimise time spent locked TimeSpan delta = blockedUntil - now; p.Leave("Too many connections too quickly! Wait " + delta.Shorten(true) + " before joining"); return(false); }
public void TestIp() { String ipaddr = "192.168.55.80"; long longIP = IPUtil.IpToLong(ipaddr); Assert.AreEqual(ipaddr, IPUtil.IpToString(longIP)); }
/// <summary> /// 记录动作 /// </summary> /// <param name="actionType"></param> public static void CreateValidateCodeActionRecode(string actionType) { foreach (ValidateCode tempValidateCode in AllSettings.Current.ValidateCodeSettings.ValidateCodes) { if (string.Compare(tempValidateCode.ActionType, actionType, true) == 0) { if (tempValidateCode.Enable == false) { return; } if (tempValidateCode.LimitedCount == 0 || tempValidateCode.LimitedTime == 0) { return; } string IP = IPUtil.GetCurrentIP(); ValidateCodeDao.Instance.CreateValidateCodeActionRecord(IP, actionType, DateTimeUtil.Now, tempValidateCode.LimitedTime, tempValidateCode.LimitedCount); string cacheKey = string.Format(cacheKey_ValidateCodeActionRecodes, IP); CacheUtil.Remove(cacheKey); break; } } }
void Form1_Load(object sender, EventArgs e) { _logger = StreamLogger.Create(new FileStream("log.log", FileMode.Append, FileAccess.Write)); Log("KeiSystem 测试程序及组件," + Rev + "。"); var possibleAddresses = Dns.GetHostEntry(IPAddress.Loopback).AddressList; foreach (var address in possibleAddresses) { if (address.AddressFamily == AddressFamily.InterNetwork && IPUtil.IsAddressIntranet(address)) { cboPossibleAddresses.Items.Add(address.ToString()); } } if (cboPossibleAddresses.Items.Count > 0) { cboPossibleAddresses.SelectedIndex = 0; } else { Log("在您的计算机上没有找到合适的内网地址,无法正常启动。"); } cboRegardAsStartTime.SelectedIndex = 0; groupBox2.Enabled = false; groupBox4.Enabled = false; }
/// <summary> /// 是否需要输验证码 /// </summary> /// <param name="actionType"></param> /// <returns></returns> public static bool HasValidateCode(string actionType) { foreach (ValidateCode tempValidateCode in AllSettings.Current.ValidateCodeSettings.ValidateCodes) { if (string.Compare(tempValidateCode.ActionType, actionType, true) == 0) { if (tempValidateCode.Enable == false) { return(false); } if (tempValidateCode.ExceptRoleIds.Count > 0) { UserRoleCollection userRoles = User.Current.Roles; foreach (UserRole role in userRoles) { if (tempValidateCode.ExceptRoleIds.Contains(role.RoleID.ToString())) { return(false); } } } if (tempValidateCode.LimitedTime == 0 || tempValidateCode.LimitedCount == 0) { return(true); } string IP = IPUtil.GetCurrentIP(); ValidateCodeActionRecordCollection recodes = GetValidateCodeActionRecodes(IP); DateTime dateTime = DateTimeUtil.Now.AddSeconds(0 - tempValidateCode.LimitedTime); int count = 0; foreach (ValidateCodeActionRecord recode in recodes) { if (string.Compare(recode.Action, actionType, true) == 0) { if (recode.CreateDate > dateTime) { count++; } } } if (count >= tempValidateCode.LimitedCount) { return(true); } return(false); } } return(false); }
public void TestNetworkAddress() { var handler = CommandGenerator.CreateAutoCommandHandler <HyperDeckSettingsSetCommand, HyperDeckSettingsGetCommand>( "NetworkAddress"); AtemMockServerWrapper.Each(_output, _pool, handler, DeviceTestCases.HyperDecks, helper => { foreach (IBMDSwitcherHyperDeck deck in GetHyperDecks(helper)) { for (int i = 0; i < 5; i++) { deck.GetId(out long id); AtemState stateBefore = helper.Helper.BuildLibState(); HyperdeckState hyperdeckState = stateBefore.Hyperdecks[(int)id]; byte[] randomIp = RandomIP(); hyperdeckState.Settings.NetworkAddress = IPUtil.IPToString(randomIp); uint ipVal = BitConverter.ToUInt32(randomIp.Reverse().ToArray()); helper.SendAndWaitForChange(stateBefore, () => { deck.SetNetworkAddress(ipVal); }); } } }); }
private void hostGameButton_Click(object sender, EventArgs e) { hostGameButton.Enabled = false; Process process = new Process(); #if DEBUG process.StartInfo.CreateNoWindow = false; process.StartInfo.FileName = "..\\..\\..\\Server\\bin\\debug\\VideoPaintballServer.exe"; #elif RELEASE process.StartInfo.CreateNoWindow = true; process.StartInfo.FileName = "..\\..\\..\\Server\\bin\\release\\VideoPaintballServer.exe"; #endif // process.StartInfo.FileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "VideoPaintballServer.exe"); process.StartInfo.UseShellExecute = true; process.Start(); //TODO: wait until server is up and listening Thread.Sleep(5000); GameConfiguration.ServerConnection = ServerConnector.ConnectToServer(IPUtil.GetLocalIpAddress()); GameConfiguration.ThisClientIsServer = true; if (GameConfiguration.ServerConnection != null) { this.Hide(); } else { hostGameButton.Enabled = true; } }
public override void OnResultExecuted(ResultExecutedContext filterContext) { if (debugLog) { var watchRender = GetTimer(filterContext, "render"); watchRender.Stop(); var watchAction = GetTimer(filterContext, "action"); string controllerName = (string)filterContext.RouteData.Values["controller"]; string actionName = (string)filterContext.RouteData.Values["action"]; builder.Append("【执行时间】").Append(watchAction.ElapsedMilliseconds).Append("ms").AppendLine(); builder.Append("【渲染时间】").Append(watchRender.ElapsedMilliseconds).Append("ms").AppendLine(); builder.Append("【本机IP】").Append(IPUtil.GetLocalIP()).AppendLine(); builder.Append("【访问路径】").AppendLine(filterContext.HttpContext.Request.RawUrl); if (filterContext.HttpContext.Response.ContentType == "application/json") { var json = filterContext.Result as ContentResult; if (json != null) { builder.Append("【响应内容】").AppendLine(json.Content); } } log.WriteToFile(builder.ToString(), "logs/{0}-{1}".Fmt(controllerName.ToLower(), actionName.ToLower())); } }
//NOTE: used in CallComplete public Endpoint GetTermEP(string pTermIP, int pDuration) { Endpoint _termEP = null; try { if (pTermIP.CompareTo("0.0.0.0") == 0) { if (pDuration > 0) { TimokLogger.Instance.LogRbr(LogSeverity.Critical, "BillingService.getTermEP", string.Format("Call duration > 0 and TermEP equal to HostIP or 0.0.0.0, TermIP: {0}", pTermIP)); } return(_termEP); } //-- get TermEP using (var _db = new Rbr_Db()) { var _endpointRow = _db.EndPointCollection.GetByIPAddress(IPUtil.ToInt32(pTermIP)); if (_endpointRow != null) { _termEP = new Endpoint(_endpointRow); } } } catch (Exception _ex) { TimokLogger.Instance.LogRbr(LogSeverity.Error, "RoutingService.GetTermEP", string.Format("getTermEP Exception:\r\n{0}", _ex)); } return(_termEP); }
public static void Main3(string[] args) { string ver = Tamir.IPLib.Version.GetVersionString(); /* Print SharpPcap version */ Console.WriteLine("SharpPcap {0}, ArpTest.cs", ver); Console.WriteLine(); /* Retrieve the device list */ PcapDeviceList devices = SharpPcap.GetAllDevices(); /*If no device exists, print error */ if (devices.Count < 1) { Console.WriteLine("No device found on this machine"); return; } Console.WriteLine("The following devices are available on this machine:"); Console.WriteLine("----------------------------------------------------"); Console.WriteLine(); int i = 0; /* Scan the list printing every entry */ foreach (PcapDevice dev in devices) { /* Description */ Console.WriteLine("{0}) {1}", i, dev.PcapDescription); i++; } Console.WriteLine(); Console.Write("-- Please choose a device for sending the ARP request: "); i = int.Parse(Console.ReadLine()); string device = devices[i].PcapName; String ip = ""; while (true) { Console.Write("-- Please enter IP address to be resolved by ARP: "); ip = Console.ReadLine(); if (IPUtil.IsIP(ip)) { break; } Console.WriteLine("Bad IP address format, please try again"); } //Create a new ARP resolver //(for more info, see: //http://www.tamirgal.com/home/SourceView.aspx?Item=SharpPcap&File=ARP.cs) ARP arper = new ARP(device); //print the resolved address Console.WriteLine(ip + " is at: " + arper.Resolve(ip)); }
public LogMessage() { this.UserId = MyContext.Instance.UserId.ToString(); this.UserName = MyContext.Instance.UserName; this.IP = string.IsNullOrEmpty(IPUtil.GetUserIP()) ? "" : IPUtil.GetUserIP(); //this.PhysicalAddress = GetPhysicalAddress(IPUtil.GetUserIP()); this.PhysicalAddress = "127.0.0.1"; }
public void testIsRangeWithDottedMask() { Assert.IsTrue(!IPUtil.IsRangeWithDottedMask("1.2.3.0/24")); Assert.IsTrue(IPUtil.IsRangeWithDottedMask("1.2.3.0 255.255.255.0")); Assert.IsTrue(!IPUtil.IsRangeWithDottedMask("1.2.3.0")); Assert.IsTrue(!IPUtil.IsRangeWithDottedMask("1.2.3.0/")); Assert.IsTrue(!IPUtil.IsRangeWithDottedMask("1.2.3.0 255.255.0")); }
public void GetIPText_Exception_IndexOutOfRange_Test() { byte[] data = new byte[] { 127, 0, 0 }; string actual = IPUtil.GetIPText(data); string expected = ""; Assert.AreEqual(expected, actual); }
public void testIsRangeWithMaskBits() { Assert.IsTrue(IPUtil.IsRangeWithMaskBits("1.2.3.0/24")); Assert.IsTrue(!IPUtil.IsRangeWithMaskBits("1.2.3.0 255.255.255.0")); Assert.IsTrue(!IPUtil.IsRangeWithMaskBits("1.2.3.0")); Assert.IsTrue(!IPUtil.IsRangeWithMaskBits("1.2.3.0/")); Assert.IsTrue(!IPUtil.IsRangeWithMaskBits("1.2.3.0 255.255.0")); }
public MainModelImpl() { /* * 1、概述 * * ado.net提供了丰富的数据库操作,这些操作可以分为三个步骤: * * 第一,使用SqlConnection对象连接数据库; * 第二,建立SqlCommand对象,负责SQL语句的执行和存储过程的调用; * 第三,对SQL或存储过程执行后返回的“结果”进行操作。 * 对返回“结果”的操作可以分为两类: * * 一是用SqlDataReader直接一行一行的读取数据集; * 二是DataSet联合SqlDataAdapter来操作数据库。 * 两者比较: * * SqlDataReader时刻与远程数据库服务器保持连接,将远程的数据通过“流”的形式单向传输给客户端,它是“只读”的。由于是直接访问数据库,所以效率较高,但使用起来不方便。 * DataSet一次性从数据源获取数据到本地,并在本地建立一个微型数据库(包含表、行、列、规则、表之间的关系等),期间可以断开与服务器的连接,使用SqlDataAdapter对象操作“本地微型数据库”, * 结束后通过SqlDataAdapter一次性更新到远程数据库服务器。这种方式使用起来更方,便简单。但性能较第一种稍微差一点。(在一般的情况下两者的性能可以忽略不计。) * * * http://www.cnblogs.com/youuuu/archive/2011/06/16/2082730.html * */ string mysqlcon = ""; //创建连接 try { //对需要输出到bin的文件,右键属性,复制到输出目录 http://blog.csdn.net/dqs78833488/article/details/52684146 string ip = IPUtil.GetLocalIpv4()[0]; mysqlcon = "database=tree;Password=root;User ID=root;server=" + ip; conn = new MySqlConnection(mysqlcon); conn.Open(); if (conn.State == System.Data.ConnectionState.Open) { LogUtil.Log("-------数据库连接成功-------"); } cmd = conn.CreateCommand(); cmd.CommandType = System.Data.CommandType.Text;//使其只执行SQL语句文本形式 try { //启动定时任务 iniTimerTask(); } catch { LogUtil.Log("定时任务启动异常"); } } catch (Exception e) { Console.WriteLine(e.ToString()); LogUtil.Log("数据库连接异常 " + mysqlcon); } }
public void GetIPTextTest() { byte[] data = new byte[] { 127, 0, 0, 1 }; string expected = "127.0.0.1"; string actual; actual = IPUtil.GetIPText(data); Assert.AreEqual(expected, actual); }
public void ParseIPEndPointTest() { string ipString = "192.168.0.1:8001"; IPEndPoint expected = new IPEndPoint(IPAddress.Parse("192.168.0.1"), 8001); IPEndPoint actual; actual = IPUtil.ParseIPEndPoint(ipString); Assert.AreEqual(expected, actual); }
private async Task <string> CallServer(string api, Dictionary <string, string> paramters, Dictionary <string, string> body, string curServer, HttpMethod method) { InjectSecurityInfo(paramters); var headers = NamingHttpUtil.BuildHeader(); var url = string.Empty; if (curServer.StartsWith(UtilAndComs.HTTPS) || curServer.StartsWith(UtilAndComs.HTTP)) { url = curServer.TrimEnd('/') + api; } else { if (IPUtil.ContainsPort(curServer)) { curServer = curServer + IPUtil.IP_PORT_SPLITER + serverPort; } // TODO http or https url = UtilAndComs.HTTP + curServer + api; } try { var client = _clientFactory?.CreateClient(ConstValue.ClientName) ?? new HttpClient(); client.Timeout = TimeSpan.FromSeconds(8); var requestUrl = $"{url}?{InitParams(paramters, body)}"; var requestMessage = new HttpRequestMessage(method, requestUrl); BuildHeader(requestMessage, headers); var responseMessage = await client.SendAsync(requestMessage).ConfigureAwait(false); if (responseMessage.IsSuccessStatusCode) { var content = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); return(content); } else if (responseMessage.StatusCode == System.Net.HttpStatusCode.NotModified) { return(string.Empty); } // response body will contains some error message var msg = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); throw new NacosException((int)responseMessage.StatusCode, $"{responseMessage.StatusCode}--{msg}"); } catch (Exception ex) { _logger?.LogError(ex, "[NA] failed to request"); throw new NacosException(NacosException.SERVER_ERROR, ex.Message); } }
private void initCanRegister() { using (ErrorScope es = new ErrorScope()) { m_CanRegister = UserBO.Instance.CanRegister(IPUtil.GetCurrentIP()); es.CatchError <ErrorInfo>(delegate(ErrorInfo error) { m_CannotRegisterReason = error.Message; }); } }
public CallState OnConnecting(LegIn pLegIn, LegOut pLegOut) { cdrAggrExporter.OnCallSetup(string.Empty, pLegOut.CarrierAcctId, pLegOut.CarrierBaseRouteId, pLegIn.CustomerAcctId, pLegIn.CustomerRouteId, IPUtil.ExtractIPAddress(pLegIn.IPAndPort), IPUtil.ExtractIPAddress(pLegOut.DestIPAndPort)); return(callStatistics.OnConnecting(pLegIn, pLegOut)); }
public static FullRouteIPInfoEntry Search(string ipStr) { try { return(Search(IPUtil.StrToIP(ipStr))); } catch { return(null); } }
public void SetIP(IPAddress addr) { // Convert IPv4 mapped addresses to IPv4 addresses for consistency // (e.g. so IPv4 mapped LAN IPs are treated as LAN IPs) if (IPUtil.IsIPv4Mapped(addr)) { addr = IPUtil.MapToIPV4(addr); } IP = addr; ip = addr.ToString(); }
public override bool IsValid(PropertyInfo prop, object obj) { try { IPUtil.ParseAddress((string)obj); return(true); } catch { return(false); } }
void createFieldIndexer() { fieldValues = new StringDictionary(); fieldValues.Add(date_logged_DbName, Date_logged.ToString()); fieldValues.Add(timok_date_DbName, Timok_date.ToString()); fieldValues.Add(start_DbName, Start.ToString()); fieldValues.Add(duration_DbName, Duration.ToString()); fieldValues.Add(ccode_DbName, Ccode.ToString()); fieldValues.Add(local_number_DbName, Local_number); fieldValues.Add(carrier_route_id_DbName, Carrier_route_id.ToString()); fieldValues.Add(price_DbName, Price.ToString()); fieldValues.Add(cost_DbName, Cost.ToString()); fieldValues.Add(orig_IP_address_DbName, IPUtil.ToString(Orig_IP_address)); fieldValues.Add(orig_end_point_id_DbName, Orig_end_point_id.ToString()); fieldValues.Add(term_end_point_id_DbName, Term_end_point_id.ToString()); fieldValues.Add(customer_acct_id_DbName, Customer_acct_id.ToString()); fieldValues.Add(disconnect_cause_DbName, Disconnect_cause.ToString()); fieldValues.Add(disconnect_source_DbName, Disconnect_source.ToString()); fieldValues.Add(rbr_result_DbName, Rbr_result.ToString()); fieldValues.Add(prefix_in_DbName, Prefix_in); fieldValues.Add(prefix_out_DbName, Prefix_out); fieldValues.Add(DNIS_DbName, DNIS.ToString()); fieldValues.Add(ANI_DbName, ANI.ToString()); fieldValues.Add(serial_number_DbName, Serial_number.ToString()); fieldValues.Add(end_user_price_DbName, End_user_price.ToString()); fieldValues.Add(used_bonus_minutes_DbName, Used_bonus_minutes.ToString()); fieldValues.Add(reseller_price_DbName, Reseller_price.ToString()); fieldValues.Add(node_id_DbName, Node_id.ToString()); fieldValues.Add(customer_route_id_DbName, Customer_acct_name); fieldValues.Add(mapped_disconnect_cause_DbName, Mapped_disconnect_cause.ToString()); fieldValues.Add(carrier_acct_id_DbName, Carrier_acct_name); fieldValues.Add(orig_dot_IP_address_DbName, Orig_dot_IP_address); fieldValues.Add(dialed_number_DbName, Dialed_number); fieldValues.Add(retail_acct_id_DbName, Retail_acct_id.ToString()); fieldValues.Add(customer_duration_DbName, Customer_duration.ToString()); fieldValues.Add(carrier_duration_DbName, Carrier_duration.ToString()); fieldValues.Add(retail_duration_DbName, Retail_duration.ToString()); fieldValues.Add(minutes_DbName, IsMinutesNull ? "<NULL>" : Minutes.ToString()); fieldValues.Add(carrier_minutes_DbName, IsCarrier_minutesNull ? "<NULL>" : Carrier_minutes.ToString()); fieldValues.Add(retail_minutes_DbName, IsRetail_minutesNull ? "<NULL>" : Retail_minutes.ToString()); fieldValues.Add(carrier_route_name_DbName, Carrier_route_name); fieldValues.Add(customer_route_name_DbName, Customer_route_name); fieldValues.Add(orig_alias_DbName, Orig_alias); fieldValues.Add(term_alias_DbName, Term_alias); fieldValues.Add(term_ip_address_range_DbName, Term_ip_address_range); fieldValues.Add(customer_acct_name_DbName, Customer_acct_name); fieldValues.Add(orig_partner_id_DbName, IsOrig_partner_idNull ? "<NULL>" : Orig_partner_id.ToString()); fieldValues.Add(orig_partner_name_DbName, Orig_partner_name); fieldValues.Add(carrier_acct_name_DbName, Carrier_acct_name); fieldValues.Add(term_partner_id_DbName, IsTerm_partner_idNull ? "<NULL>" : Term_partner_id.ToString()); fieldValues.Add(term_partner_name_DbName, Term_partner_name); fieldValues.Add(node_name_DbName, Node_name); }
/// <summary> /// Resolves the MAC address of the specified IP address /// </summary> /// <param name="destIP">The IP address to resolve</param> /// <param name="deviceName">The local network device name on which to send the ARP request</param> /// <returns>The MAC address that matches to the given IP address</returns> public string Resolve(String destIP, string deviceName) { string localMAC = LocalMAC; string localIP = LocalIP; NetworkDevice device = new NetworkDevice(DeviceName); //if no local IP and MAC addresses specified, use the ones //configured on the local device if (localIP == null) { localIP = device.IpAddress; } if (LocalMAC == null) { localMAC = device.MacAddress; } //Build a new ARP request packet ARPPacket request = BuildRequest(destIP, localMAC, localIP); //create a "tcpdump" filter for allowing only arp replies to be read String arpFilter = "arp and ether dst " + IPUtil.MacFormat(localMAC); //open the device with 20ms timeout device.PcapOpen(true, 20); //set the filter device.PcapSetFilter(arpFilter); //inject the packet to the wire device.PcapSendPacket(request); ARPPacket reply; while (true) { //read the next packet from the network reply = (ARPPacket)device.PcapGetNextPacket(); if (reply == null) { continue; } //if this is the reply we're looking for, stop if (reply.ARPSenderProtoAddress.Equals(destIP)) { break; } } //free the device device.PcapClose(); //return the resolved MAC address return(reply.ARPSenderHwAddress); }