public static void Connect(Loop loop, IPAddress ipAddress, int port, Action<Exception, Tcp> callback) { Ensure.ArgumentNotNull(loop, "loop"); Ensure.ArgumentNotNull(ipAddress, "ipAddress"); Ensure.ArgumentNotNull(callback, "callback"); ConnectRequest cpr = new ConnectRequest(); Tcp socket = new Tcp(loop); cpr.Callback = (status, cpr2) => { if (status == 0) { callback(null, socket); } else { socket.Close(); callback(Ensure.Success(loop), null); } }; int r; if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { r = uv_tcp_connect(cpr.Handle, socket.handle, UV.uv_ip4_addr(ipAddress.ToString(), port), CallbackPermaRequest.StaticEnd); } else { r = uv_tcp_connect6(cpr.Handle, socket.handle, UV.uv_ip6_addr(ipAddress.ToString(), port), CallbackPermaRequest.StaticEnd); } Ensure.Success(r, loop); }
/// <summary> /// Actual command logic /// </summary> /// <param name="source">The user who triggered the command.</param> /// <param name="channel">The channel the command was triggered in.</param> /// <param name="args">The arguments to the command.</param> /// <returns></returns> protected override CommandResponseHandler execute(User source, string channel, string[] args) { if (args[0].Length != 8) return null; byte[] ip = new byte[4]; ip[0] = Convert.ToByte(args[0].Substring(0, 2), 16); ip[1] = Convert.ToByte(args[0].Substring(2, 2), 16); ip[2] = Convert.ToByte(args[0].Substring(4, 2), 16); ip[3] = Convert.ToByte(args[0].Substring(6, 2), 16); IPAddress ipAddr = new IPAddress(ip); string hostname = ""; try { hostname = Dns.GetHostEntry(ipAddr).HostName; } catch (SocketException) { } if (hostname != string.Empty) { string[] messageargs = {args[0], ipAddr.ToString(), hostname}; return new CommandResponseHandler(new Message().get("hexDecodeResult", messageargs)); } else { string[] messageargs = {args[0], ipAddr.ToString()}; return new CommandResponseHandler(new Message().get("hexDecodeResultNoResolve", messageargs)); } }
public static int Main() { IPAddress testadd = IPAddress.Parse ("127.0.0.1"); Console.WriteLine("address is " + testadd.Address.ToString ("X")); if (testadd.Address != 0x0100007f) return 1; IPAddress hostadd = new IPAddress(0x0100007f); Console.WriteLine("address is " + hostadd.ToString()); if (hostadd.ToString() != "127.0.0.1") return 1; return 0; }
protected override void tcpClosed(IPAddress ip, int port) { for(LinkedListNode<IPEndPoint> it = clientIPEndPoints.First; it != null; it = it.Next) { if(it.Value.Address.ToString() == ip.ToString()) { clientIPEndPoints.Remove(it); break; } } for(LinkedListNode<TcpClient> it = tcpClients.First; it != null; it = it.Next) { IPEndPoint iep = (IPEndPoint)it.Value.Client.RemoteEndPoint; if(iep.Address.ToString() == ip.ToString()) { tcpClients.Remove(it); break; } } for (LinkedListNode<IPAddress> it = clientIPAdresses.First; it != null; it = it.Next) { if (it.Value.ToString() == ip.ToString()) { clientIPAdresses.Remove(it); break; } } recyclePort(port); label1.Text = clientIPEndPoints.Count().ToString() + " Client(s) Online"; }
private void UpdateWithUserIp(string name, IPAddress ip) { BannedUser b; if (GetByIp(ip.ToString(), out b)) if (!b.nickNames.Contains(name)) b.nickNames.Add(name); if (GetByName(name, out b)) if (ip != IPAddress.None && !b.ipAddresses.Contains(ip.ToString())) b.ipAddresses.Add(ip.ToString()); if (b != null) { if (b.Expired) Items.Remove(b); Save(); } }
public void AddServer(IPAddress ip) { foreach (var m in MenuEntries) if (m.Text == ip.ToString()) return; MenuEntry server = new MenuEntry(ip.ToString()); server.Selected += ServerMenuEntrySelected; MenuEntries.Add(server); }
public void Log(String username, IPAddress addr) { String baseDirecotry = Directory.GetCurrentDirectory(); AppendPath(ref baseDirecotry, "Logs"); AppendPath(ref baseDirecotry, "IpLogs"); String generalLog = Path.Combine(baseDirecotry, "ip.log"); String userLog = Path.Combine(baseDirecotry, String.Format("{0}.log", username)); using (StreamWriter sw = new StreamWriter(generalLog, true)) sw.WriteLine("Account: " + username + " ha loggato con ip " + addr.ToString() + " in Data: " + DateTime.Now); using (StreamWriter sw = new StreamWriter(userLog, true)) sw.WriteLine("Account: " + username + " ha loggato con ip " + addr.ToString() + " in Data: " + DateTime.Now); }
public override void Update(HostConfig HC, IPAddress ipAddress) { if (HC == null) throw new ArgumentNullException("HC"); if (ipAddress == null) throw new ArgumentNullException("ipAddress"); using (RMWebClient WC = new RMWebClient()) { WC.ContentType = "application/xml"; WC.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(HC.Username + ":" + HC.Password.GetPlainText())); WC.Headers["Accept"] = "application/xml"; WC.UseDefaultCredentials = false; try { string Url = "https://pointhq.com"; Url += "/zones/" + HC.ProviderSpecificSettings[HostConfig.POINT_ZONE_ID]; Url += "/records/" + HC.ProviderSpecificSettings[HostConfig.POINT_RECORD_ID]; string ResponseText = WC.UploadString(Url, "PUT", "<zone-record><data>" + ipAddress.ToString() + "</data><ttl type=\"integer\">60</ttl></zone-record>").Trim(); if (!ResponseText.Contains(ipAddress.ToString())) { HC.Disabled = true; HC.DisabledReason = "Reason not known."; HC.Save(); Logging.instance.LogError("Unable to update host \"" + HC.Hostname + "\" (" + HC.Provider.ToString() + "): " + HC.DisabledReason); } } catch (WebException wex) { HC.Disabled = true; switch (((HttpWebResponse)wex.Response).StatusCode) { case HttpStatusCode.Forbidden: HC.DisabledReason = "Current user does not have access to requested resource."; break; case HttpStatusCode.NotFound: HC.DisabledReason = "Record not found."; break; default: HC.DisabledReason = "An unknown response code was received: \"" + ((HttpWebResponse)wex.Response).StatusCode + "\""; break; } HC.Save(); Logging.instance.LogError("Unable to update host \"" + HC.Hostname + "\" (" + HC.Provider.ToString() + "): " + HC.DisabledReason); } catch (Exception ex) { HC.Disabled = true; HC.DisabledReason = "Unhandled exception (" + ex.Message + ")"; HC.Save(); Logging.instance.LogException("Unable to update host \"" + HC.Hostname + "\"", ex); } } }
/// <summary> /// Adds a potential IP address /// </summary> /// <param name="addr"></param> public void addPotential(IPAddress addr) { if (potentialIPBox.InvokeRequired) { potentialIPBox.Invoke((MethodInvoker)delegate { addPotential(addr); }); } else { if (!potentialIPBox.Items.Contains(addr.ToString())) this.potentialIPBox.Items.Add(addr.ToString()); } }
private static string TryGetHostName(IPAddress address) { string hostName = null; try { var hostEntry = Dns.GetHostEntry(address); hostName = hostEntry != null ? hostEntry.HostName : address.ToString(); } catch { //Whatever happens, just return address.ToString(); hostName = address.ToString(); } return hostName; }
public static string GetNetworkAddressAsString(IPAddress address, IPAddress mask) { string netIP = ""; // Network address as string int networkLength = 0; if (null != mask) { for (int i = 0; i < 4; i++) { byte ba = address.GetAddressBytes()[i]; byte bm = mask.GetAddressBytes()[i]; netIP += ba & bm; if (i < 3) netIP += "."; networkLength += 8 - (int)System.Math.Truncate(System.Math.Log(256 - bm, 2)); } netIP += "/" + networkLength; } else { netIP = address.ToString() + "/32"; } return netIP; }
/// <summary> /// 判断用户是否注册 /// </summary> /// <param msg="ClassMsg"></param> /// <param Ip="System.Net.IPAddress"></param> /// <param Port="int"></param> /// <returns></returns> private bool IfRegisterAt(ClassMsg msg, System.Net.IPAddress Ip, int Port) { bool RegAt = true; //RegisterMsg registermsg = (RegisterMsg)new ClassSerializers().DeSerializeBinary(new MemoryStream(msg.Data)); ClassOptionData OptionData = new ClassOptionData(); MsgCommand Sate = msg.msgCommand; String UserName = msg.UserName; //注册用户的名称 String PassWord = msg.PassWord; //注册用户的密码 String vIP = Ip.ToString(); //注册用户的IP地址 SqlDataReader DataReader; //查找注册用户 DataReader = OptionData.ExSQLReDr("Select * From tb_Gobang where UserName="******"'" + UserName + "'"); if (DataReader.Read()) { RegAt = true; msg.msgCommand = MsgCommand.RegisterAt; //存在注册用户 SendMsgToOne(Ip, Port, msg); //将注册命令返回给注册用户 } else { DataReader = OptionData.ExSQLReDr("Select * From tb_Gobang where IP=" + "'" + Ip.ToString() + "'"); if (DataReader.Read()) { OptionData.ExSQL("Delete tb_Gobang where IP=" + "'" + Ip.ToString() + "'"); } RegAt = false; msg.msgCommand = MsgCommand.Registered;//用户注册结束命令 } return(RegAt); }
public IPBanInfo Get( IPAddress address ) { lock( locker ) { if( bans.ContainsKey( address.ToString() ) ) { return bans[address.ToString()]; } else { return null; } } }
private byte[] decMessage; // the decrypted bytes - s/b same as message public Server() { InitializeComponent(); Pkey.Text = ""; Qkey.Text = ""; Nkey.Text = ""; Phikey.Text = ""; NODkey.Text = ""; Dkey.Text = ""; Ykey.Text = ""; Ekey.Text = ""; String strHostName; strHostName = Dns.GetHostName(); System.Net.IPAddress ip = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList[0]; myIP.Text += ip.ToString(); ipadress.Text = ip.ToString(); }
public Client() { InitializeComponent(); String strHostName; strHostName = Dns.GetHostName(); System.Net.IPAddress ip = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList[0]; myIP.Text += ip.ToString(); ipadress.Text = ip.ToString(); logs.Text += "===Начало работы===\r\n"; }
public static bool VerificationIPAddress(IPAddress ip) { if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { return VerificationIPAddressV4(ip.ToString()); } else if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) { if (ip.IsIPv6LinkLocal == true || ip.IsIPv6Multicast == true || ip.IsIPv6SiteLocal == true) return false; else return VerificationIPAddressV6(ip.ToString()); } return false; }
// Use this for initialization void Start() { // Transport 클래스의 컴포넌트를 가져온다. #if USE_TRANSPORT_TCP GameObject obj = GameObject.Instantiate(transportTcpPrefab) as GameObject; m_transport = obj.GetComponent <TransportTCP>(); m_transport.RegisterEventHandler(test); #else GameObject obj = GameObject.Instantiate(transportUdpPrefab) as GameObject; m_transport = obj.GetComponent <TransportUDP>(); #endif IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); System.Net.IPAddress hostAddress = hostEntry.AddressList[0]; m_strings = hostAddress.ToString(); Debug.Log(m_strings); // 얻은 주소체계를 모두 출력 string ClientIP = string.Empty; Debug.Log("hostEntry.AddressList.Length : " + hostEntry.AddressList.Length); for (int i = 0; i < hostEntry.AddressList.Length; i++) { ClientIP = hostEntry.AddressList[i].ToString(); Debug.Log(i + ", ClientIP : " + ClientIP + " " + hostEntry.AddressList[i].AddressFamily); //if(hostEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork) //{ // // 실제 접속할 IP // ClientIP = hostEntry.AddressList[i].ToString(); //} } }
public void UpdateDnsRecords(string domain, IPAddress newPublicIp) { var uriFormat = ConfigurationManager.AppSettings[AppSettingsKeys.ZerigoUpdateUriFormat]; var uri = uriFormat .Replace("$DOMAIN$", domain) .Replace("$IP$", newPublicIp.ToString()) .Replace("$USERNAME$", this.configSection.Credentials.UserName) .Replace("$APIKEY$", this.configSection.Credentials.ApiKey); this.log.Info( "Updating the DNS record for {0} to {1} using the following uri: {2}.", domain, newPublicIp, uri); var response = this.client.GetAsync(uri).Result; switch (response.StatusCode) { case HttpStatusCode.Forbidden: case HttpStatusCode.Unauthorized: this.log.Error("The server returned authentication error, please verify your user name and the API key."); break; case HttpStatusCode.InternalServerError: this.log.Error("There seems to be an issue with the zerigo.com website. The application will retry in the defined interval."); break; } response.EnsureSuccessStatusCode(); this.log.Info("DNS record update was successful."); }
public static List <DeviceDiscoveryData> GetDevices( SoapMessage <WSD.ProbeMatchesType> message, Net.IPAddress sender, DiscoveryType[][] types) { List <DeviceDiscoveryData> devices = new List <DeviceDiscoveryData>(); if (message.Object.ProbeMatch != null) { for (int i = 0; i < message.Object.ProbeMatch.Length; i++) { WSD.ProbeMatchType match = message.Object.ProbeMatch[i]; if ((match.XAddrs != null) && (types == null //check devices according to Test Spec Annex A.1 ? CheckDeviceMatchType(message, i, true, false) //check if device contains at least one item from types array : CheckDeviceMatchType(message, i, types))) { DeviceDiscoveryData device = new DeviceDiscoveryData(); device.Type = match.Types; device.Scopes = match.Scopes.Text[0]; device.EndPointAddress = sender.ToString(); string[] addresses = match.XAddrs.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); device.ServiceAddresses.AddRange(addresses); device.UUID = match.EndpointReference.Address.Value; device.MetadataVersion = match.MetadataVersion; devices.Add(device); } } } return(devices); }
private void connect_Click(object sender, EventArgs e) { System.Net.IPAddress address = null; if (System.Net.IPAddress.TryParse(ipAddress.Text, out address)) { Status.Text = "Connecting to " + address.ToString(); c = new PJLinkConnection(ipAddress.Text, "JBMIAProjectorLink"); LampStatusCommand l = new LampStatusCommand(); int hours = l.getHoursOfLamp(1); string status = l.getStatusOfLamp(1).ToString(); string power = c.powerQuery().ToString(); ProjectorInfo pi = new ProjectorInfo(); Status.Text = "Connected. \n Projector is now: " + power + "\n" + "\nstatus: " + status + "\nlamphours: " + hours; Status.Text += "\nFan:" + pi.FanStatus; Status.Text += " Lamp:" + pi.LampStatus; Status.Text += " Input:" + pi.Input; Status.Text += "\nCover:" + pi.CoverStatus; Status.Text += " Filter:" + pi.FilterStatus; Status.Text += " NumLamps:" + pi.NumOfLamps; Status.Text += "\nOthers:" + pi.PowerStatus; } else { Status.Text = "Invalid IP Address Entered"; } }
/// <summary> /// 用户登录 /// </summary> /// <param name="msg"></param> /// <param name="Ip"></param> /// <param name="Port"></param> /// <param name="State"></param> private void UserLogin(ClassMsg msg, System.Net.IPAddress Ip, int Port, int State) { RegisterMsg registermsg = (RegisterMsg) new ClassSerializers().DeSerializerBinary(new MemoryStream(msg.Data)); ClassOptionData OptionData = new ClassOptionData(); //创建并引用ClassOptionData MsgCommand msgState = msg.msgCommand; //获取接收消息的命令 String UserName = registermsg.UserName; //登录用户名称 String PassWord = registermsg.PassWord; //用户密码 String vIP = Ip.ToString(); //用户IP地址 SqlDataReader DataReader = OptionData.ExSQLReader("Select * From tb_CurreneyUser Where Name = " + "'" + UserName + "'" + " and PassWord = "******"'" + PassWord + "'"); //在数据库中通过用户名和密码进行查找 DataReader.Read(); //读取查找到的记录 string ID = Convert.ToString(DataReader.GetInt32(0)); //获取第一条记录中的ID字段值 if (DataReader.HasRows) //当DataReader中有记录信息时 { //修改当前记录的标识为上线状态 OptionData.ExSQL("Update tb_CurreneyUser Set Sign = " + Convert.ToString((int)(MsgCommand.Logined)) + ",IP = " + "'" + vIP + "',Port = " + "'" + Port.ToString() + "'" + " Where ID = " + ID); msg.msgCommand = MsgCommand.Logined; //设置为上线命令 msg.SID = ID; //用户ID值 SendMsgToOne(Ip, Port, msg); //将消息返回给发送用户 UpdateUserState(msg, Ip, Port); //更新用户在线状态 } OptionData.Dispose(); UpdateUser();//更新用户列表 }
/// <summary> /// Gets the country code for a string IP address /// </summary> /// <param name="IP"></param> /// <returns></returns> public static string GetCountryCode(IPAddress IP) { // Return default config Country Code if (IPAddress.IsLoopback(IP) || HttpServer.LocalIPs.Contains(IP)) return Program.Config.ASP_LocalIpCountryCode; try { using (DatabaseDriver Driver = new DatabaseDriver(DatabaseEngine.Sqlite, ConnectionString)) { // Fetch country code from Ip2Nation Driver.Connect(); List<Dictionary<string, object>> Rows = Driver.Query( "SELECT country FROM ip2nation WHERE ip < @P0 ORDER BY ip DESC LIMIT 1", Networking.IP2Long(IP.ToString()) ); string CC = (Rows.Count == 0) ? "xx" : Rows[0]["country"].ToString(); // Fix country! return (CC == "xx" || CC == "01") ? Program.Config.ASP_LocalIpCountryCode : CC; } } catch { return Program.Config.ASP_LocalIpCountryCode; } }
internal bool Initialize(System.Net.IPAddress ipAddr, int port, string prefix) { try { server = new HttpListener(); string listenerAddress = String.Format("http://+:{0}{1}", port, prefix); logger.Log("Trying system http server for " + listenerAddress); server.Prefixes.Add(listenerAddress); server.Start(); if (ipAddr == IPAddress.Any) { address = new Uri(String.Format("http://{0}:{1}{2}", Environment.MachineName, port, prefix)); } else { address = new Uri(String.Format("http://{0}:{1}{2}", ipAddr.ToString(), port, prefix)); } logger.Log("Got system http server for " + address.AbsoluteUri); return(true); } catch (HttpListenerException e) { logger.Log("Failed to get system http server: " + e.Message); server = null; return(false); } }
/// <summary> /// 更改登录用户 /// </summary> /// <param name="msg"></param> /// <param name="Ip"></param> /// <param name="Port"></param> /// <returns></returns> private ClassMsg UpdateLoginUser(ClassMsg msg, System.Net.IPAddress Ip, int Port) { //RegisterMsg registermsg = (RegisterMsg)new ClassSerializers().DeSerializeBinary(new MemoryStream(msg.Data)); ClassOptionData OptionData = new ClassOptionData(); //创建并引用ClassOptionData MsgCommand msgState = msg.msgCommand; //获取接收消息的命令 String UserName = msg.UserName; //登录用户名称 String PassWord = msg.PassWord; //用户密码 String vIP = Ip.ToString(); //用户IP地址 SqlDataReader DataReader = OptionData.ExSQLReDr("Select * From tb_Gobang Where UserName = "******"'" + UserName + "'" + " and PassWord = "******"'" + PassWord + "'");//在数据库中通过用户名和密码进行查找 if (DataReader.HasRows) { DataReader.Read(); //读取查找到的记录 string ID = Convert.ToString(DataReader.GetInt32(0)); //获取第一条记录中的ID字段值 msg.Fraction = DataReader.GetInt32(5); //获取当前用户的分数 msg.Sex = DataReader.GetInt32(13); //获取当前用户性别 //修改当前记录的标识为上线状态 OptionData.ExSQL("Update tb_Gobang Set State = " + Convert.ToString((int)(MsgCommand.Logined)) + ",IP = " + "'" + vIP + "',Port = " + "'" + Port.ToString() + "'" + " Where ID = " + ID); msg.msgCommand = MsgCommand.Logined; //设置为上线命令 SendMsgToOne(Ip, Port, msg); //将消息返回给发送用户/////--------------------------------//// UpdateUser(); //更新用户列表 } return(msg); }
bool ValidateAuthToken(string authToken) { try { string Message = "ControllergetopService ValidateAuthToken() authToken:" + authToken; InsertBrokerOperationLog.AddProcessLog(Message); OperationContext context = OperationContext.Current; MessageProperties prop = context.IncomingMessageProperties; RemoteEndpointMessageProperty endpoint = prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; System.Net.IPAddress ip = System.Net.IPAddress.Parse(endpoint.Address); System.Net.IPAddress _reqIp = ConverttoIP(authToken); if (ip.ToString() == _reqIp.ToString()) { return(true); } else { return(true); } } catch (Exception ex) { string Message = "ControllergetopService ValidateAuthToken() Exception:" + ex.Message; InsertBrokerOperationLog.AddProcessLog(Message); } return(true); }
/// <summary> /// Возвращает IP адрес данного компьютера /// </summary> /// <returns></returns> private string GetCurrentMachineIP() { String host = System.Net.Dns.GetHostName(); System.Net.IPAddress ip = System.Net.Dns.GetHostByName(host).AddressList[0]; return(ip.ToString()); }
private static bool IsPortOpen(IPAddress ipAddress, int currentPort, int connectTimeout) { bool portIsOpen = false; //use raw Sockets //using TclClient along with IAsyncResult can lead to ObjectDisposedException on Linux+Mono Socket socket = null; try { socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, false); IAsyncResult result = socket.BeginConnect(ipAddress.ToString(), currentPort, null, null); result.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(connectTimeout), true); portIsOpen = socket.Connected; } catch { } finally { if (socket != null) socket.Close(); } return portIsOpen; }
public POIBroadcast() { //Find current broadcast address broadCastAddr = IPAddress.Parse("192.168.1.255"); IPAddress[] localAddresses = Dns.GetHostAddresses(Dns.GetHostName()); foreach (IPAddress ip in localAddresses) { if (ip.AddressFamily == AddressFamily.InterNetwork) { //Find local address localAddr = ip; Console.WriteLine(ip.ToString()); //Find broadcast address byte[] bcBytes = IPAddress.Broadcast.GetAddressBytes(); Array.Copy(localAddr.GetAddressBytes(), bcBytes, 3); broadCastAddr = new IPAddress(bcBytes); Console.WriteLine(broadCastAddr.ToString()); } } //Initialize a broadcast channel using UDP broadCastChannel = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); broadCastChannel.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true); }
/// <summary> /// ��ȡһ��ip��ַ��mac��ַ /// </summary> /// <param name="macip">Ŀ��ip��ַ</param> /// <param name="formatstr">mac��ַ��ʽ�����ַ���</param> /// <returns></returns> public static string GetMacAddress(IPAddress ip, string formatstr) { StringBuilder strReturn = new StringBuilder(); try { Int32 remote = inet_addr(ip.ToString()); Int64 macinfo = new Int64(); Int32 length = 6; SendARP(remote, 0, ref macinfo, ref length); string temp = System.Convert.ToString(macinfo, 16).PadLeft(12, '0').ToUpper(); int x = 12; for (int i = 0; i < 6; i++) { if (i == 5) { strReturn.Append(temp.Substring(x - 2, 2)); } else { strReturn.Append(temp.Substring(x - 2, 2) + formatstr); } x -= 2; } return strReturn.ToString(); } catch { return strReturn.ToString(); } }
public ServerHost(IPAddress ip, int port) { IP = ip; Port = port; _serverListener = new TcpListener(IP, Port); Helper.LogConsole("Host", string.Format("Server opening on {0}:{1}", IP.ToString(), Port.ToString())); }
public Client(string ip, int port) { flagConnection = false; currentUser = new User(); try { IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(ip), port); _Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _Client.Connect(ipEndPoint); String Host = System.Net.Dns.GetHostName(); System.Net.IPAddress MyIp = Dns.GetHostByName(Host).AddressList[0]; string StringMyIp = MyIp.ToString(); byte[] Buffer = Encoding.UTF8.GetBytes(StringMyIp); _Client.Send(Buffer); flagConnection = true; } catch (Exception e) { } }
static void Main(string[] args) { Byte[] ip = new Byte[4]; ip[0] = 192; ip[1] = 168; ip[2] = 100; ip[3] = 0; IPAddress testIP = new IPAddress(ip); Console.WriteLine("Networkaddress: " + testIP.ToString()); //test incrementing Console.WriteLine("Test pinging:"); IPAddress y = testIP; //ping scan network for (int i =0; i<255; i++) { ping(y); y = IncrementIP(y); Console.WriteLine(y.ToString()); } //print results int count = 0; foreach(IPAddress i in pingbar) { Console.WriteLine("Reachable: " + i.ToString()); count++; } Console.WriteLine("Count: " + count); Console.WriteLine(); //Pause String x = Console.ReadLine(); }
// Use this for initialization void Start() { ID = GameObject.Find("StartClient_Button").GetComponent <IP_Input>().id; address = GameObject.Find("StartClient_Button").GetComponent <IP_Input>().ip; state = State.SelectHost; IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); System.Net.IPAddress hostAddress = hostEntry.AddressList[0]; //address = hostAddress.ToString(); m_connection = new EndPoint_Connection(); m_connection.connectionIP = hostAddress.ToString(); m_connection.ID = ID; RequestConnection(); positionSync.ID = ID; obj = GameObject.Find("Player"); receive_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); receive_socket.Bind(new IPEndPoint(IPAddress.Any, receive_port)); state = State.SendPosition; var thread = new Thread(Loop); thread.Start(); }
private static long ConvertIPAddressToNumber( IPAddress addr ) { // Convert an IP Address, (e.g. 127.0.0.1), to the numeric equivalent string[] address = addr.ToString().Split( '.' ); if( ( address.Length - 1 ) == 3 ) { return ( (long)( 16777216*Convert.ToDouble( address[0] ) + 65536*Convert.ToDouble( address[1] ) + 256*Convert.ToDouble( address[2] ) + Convert.ToDouble( address[3] ) ) ); } else { return 0; } // long ipnum = 0; // byte[] b = BitConverter.GetBytes(addr.Address); // for (int i = 0; i < 4; ++i) // { // long y = b[i]; // if (y < 0) // { // y += 256; // } // ipnum += y << ((3 - i) * 8); // } // Console.WriteLine(ipnum); // return ipnum; }
// Use this for initialization void Start() { IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); System.Net.IPAddress hostAddress = hostEntry.AddressList[0]; foreach (IPAddress ip in hostEntry.AddressList) //IP v4 { if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { hostAddress = ip; } } Debug.Log(hostEntry.HostName); m_hostAddress = hostAddress.ToString(); GameObject go = new GameObject("Network"); m_transport = go.AddComponent <TransportTCP>(); m_transport.RegisterEventHandler(OnEventHandling); m_message = new List <string> [CHAT_MEMBER_NUM]; for (int i = 0; i < CHAT_MEMBER_NUM; ++i) { m_message[i] = new List <string>(); } }
/// <summary> /// Check if a port is open to the world using a port checker /// </summary> /// <param name="externalIP">IP addrress to probe</param> /// <param name="intPortNumber">Port number to check</param> /// <returns>boolean indicating if the port is accesible from the outside world</returns> public static bool CheckExternalPort(IPAddress externalIP, int intPortNumber) { string strUrl = "http://yams.in/check-port.php?s=" + externalIP.ToString() + "&p=" + intPortNumber.ToString(); WebClient wcCheckPort = new WebClient(); UTF8Encoding utf8 = new UTF8Encoding(); string strResponse = ""; try { strResponse = utf8.GetString(wcCheckPort.DownloadData(strUrl)); switch (strResponse) { case "open": return true; case "closed": return false; default: return false; } } catch (WebException e) { YAMS.Database.AddLog("Unable to check open port: " + e.Data, "utils", "warn"); return false; } }
public static Uri Replace(Uri url, IPAddress ip) { var newUriBuilder = new UriBuilder(url); newUriBuilder.Host = ip.ToString(); var newUri = newUriBuilder.Uri; return newUri; }
public FrameUploader(string id, IPAddress address, int port) { _host = new HostName(address.ToString()); _port = port.ToString(); _cameraId = id; UploadComplete = () => { }; }
public static string GetIPAddress() { System.Net.IPAddress addr; // 获得本机局域网IP地址 addr = new System.Net.IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address); return(addr.ToString()); }
/// <summary> /// Returns a string representation of an <see cref="IPAddress"/> in the form <c>123.123.123.123</c> (for IPv4 addresses) /// or <c>ABCD:ABCD::ABCD</c> (for IPv6 addresses). This method is different from the <see cref="IPAddress.ToString"/> /// method; it avoids the zone index which is added to IPv6 addresses by that method. /// </summary> /// <param name="address">IP address to create a textural representation for. May be of address family /// <see cref="AddressFamily.InterNetwork"/> or <see cref="AddressFamily.InterNetworkV6"/>.</param> /// <returns>String representation of the given ip address.</returns> public static string IPAddrToString(IPAddress address) { string result = address.ToString(); int i = result.IndexOf('%'); if (i >= 0) result = result.Substring(0, i); return result; }
private void btStart_Click(object sender, EventArgs e) { if (serverEnabled) { Console.WriteLine("starting server " + serverAddress.ToString()); Console.WriteLine("waiting for client..."); // Start listening for connections on our IP address + Our Port number listener = new TcpListener(serverAddress, port); Console.WriteLine("Listener started on port: " + port); listener.Start(); Console.WriteLine("starting to listen"); // Is someone trying to call us? Well answer! ourTCP_Client = listener.AcceptTcpClient(); Console.WriteLine("client connected...? " + ourTCP_Client.Connected); //A network stream object. We'll use this to send and receive our data, so create a buffer for it... ourStream = ourTCP_Client.GetStream(); Console.WriteLine("client connected..."); } device.StartDacq(); btMeaDevice_present.Enabled = false; cbDevices.Enabled = false; btStart.Enabled = false; btStop.Enabled = true; firstOctet.Enabled = false; secondOctet.Enabled = false; thirdOctet.Enabled = false; fourthOctet.Enabled = false; portText.Enabled = false; }
public static string UIntToIpString(uint ipAddressInt) { var ipAddress = new System.Net.IPAddress(BitConverter.GetBytes(ipAddressInt)); var ipAddressString = ipAddress.ToString(); return(ipAddressString); }
public Settings(IPAddress defaultIP) { InitializeComponent(); ip = defaultIP; IpAddressBox.Text = ip.ToString(); }
/// <summary> /// 将[long型]数字转换为IP地址 杨栋添加 /// </summary> /// <param name="strNum">数字</param> /// <returns>返回IP地址</returns> public static string LongToIP(long strNum) { var numip = new IPAddress(strNum); string[] addressIP = numip.ToString().Split('.'); string IP = addressIP[3] + "." + addressIP[2] + "." + addressIP[1] + "." + addressIP[0]; return IP; }
public HttpResponseMessage Get(IPAddress ip) { return new HttpResponseMessage { Content = new StringContent(ip != null ? ip.ToString() : "unknown") }; }
private static Request CreateRequest(Service service, IPAddress clientIpAddress, string uuid) { var request = service.CreateAuthorizationRequest(); request.Set("uuid", uuid); request.Set("ipAddress", clientIpAddress.ToString()); return request; }
public Server(IPAddress ip, int port) { console = new consoleUI(); int maxPlayers = 3; player = new Client[maxPlayers]; reservedIDs = new Boolean[maxPlayers]; for (int i = 0; i < reservedIDs.Length; i++) { reservedIDs[i] = false; } try { tcpListener = new TcpListener(IPAddress.Any, port); tcpListener.Start(); } catch (Exception exp) { console.consoleW("Beim Versuch der Auflösung der Addresse: " + ip.ToString() + " enstand folgender Fehler:\r\n" + exp.Message, "error"); while (true) ; } }
public static List <DeviceDiscoveryData> GetDevices(SoapMessage <WSD.ProbeMatchesType> message, Net.IPAddress sender) { List <DeviceDiscoveryData> devices = new List <DeviceDiscoveryData>(); if (message.Object.ProbeMatch != null) { for (int i = 0; i < message.Object.ProbeMatch.Length; i++) { WSD.ProbeMatchType match = message.Object.ProbeMatch[i]; if ((match.XAddrs != null) && (CheckDeviceMatchType(message, i))) { DeviceDiscoveryData device = new DeviceDiscoveryData(); device.Type = match.Types; device.Scopes = match.Scopes.Text[0]; device.EndPointAddress = sender.ToString(); string[] addresses = match.XAddrs.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); device.ServiceAddresses.AddRange(addresses); device.UUID = match.EndpointReference.Address.Value; device.MetadataVersion = match.MetadataVersion; devices.Add(device); } } } return(devices); }
protected void Button1_Click(object sender, EventArgs e) { if (this.IsValid != true) { return; } string sql = @"INSERT INTO [disscuss] ([Unickname] ,[Uqq] ,[address] ,[IP] ,[Usex] ,[phonnumber] ,[registernumber] ,[content] ,[Uemail] ,[disscusstotalID]) VALUES (@Unickname ,@Uqq ,@address ,@IP ,@Usex ,@phonnumber ,@registernumber ,@content ,@Uemail ,@disscusstotalID)"; Dictionary <string, object> p = new Dictionary <string, object>(); p.Add("@Unickname", this.tbPetName.Text.Replace(" ", "")); if (this.rblGender.SelectedValue == string.Empty) { p.Add("@Usex", DBNull.Value); } else { p.Add("@Usex", this.rblGender.SelectedValue); } string hostname = Dns.GetHostName(); IPHostEntry localhost = Dns.GetHostEntry(hostname); System.Net.IPAddress addr = new System.Net.IPAddress(Dns.GetHostByName(hostname).AddressList[0].Address); p.Add("@Uqq", this.tbQQ.Text); p.Add("@phonnumber", this.tbphonnumber.Text); p.Add("@registernumber", this.tbregisternumber.Text); p.Add("@Uemail", this.tbEmail.Text.Replace(" ", "")); p.Add("@address", this.tbAddress.Text.Replace(" ", "")); p.Add("@IP", addr.ToString()); p.Add("@content", this.tbContent.Text); p.Add("@disscusstotalID", this.ddlMessageType.SelectedValue); SqlHelper.ExecuteNonQuery(sql, p); Response.Redirect("MYmessage.aspx"); }
private static string getIPAddress() { System.Net.IPAddress addr; addr = new System.Net.IPAddress(Dns.GetHostByName( Dns.GetHostName()).AddressList[0].Address); return(addr.ToString()); }
/// <summary> /// Advertise that you are joining a server. Hint: IPAddress.Parse("192.168.1.44") /// </summary> /// <param name="serverType">The servers IP</param> /// <param name="ipAddress">IPAddress tempIp = IPAddress.Parse("192.168.1.44"); </param> /// <param name="port">The servers port</param> public void AdvertiseGame(CSteamID serverType, System.Net.IPAddress ipAddress, ushort port) { //int intAddress = BitConverter.ToInt32(IPAddress.Parse(ipAddress.ToString).GetAddressBytes(), 0); //string tempIp = new IPAddress(BitConverter.GetBytes(intAddress)).ToString(); uint tempIp = ToUInt(ipAddress.ToString()); SteamUser.AdvertiseGame(serverType, tempIp, port); }
/// <summary> /// Get Local IP Address /// </summary> public string GetLocalAddresses() { // 获取主机名 string strHostName = Dns.GetHostName(); System.Net.IPAddress addr; addr = new System.Net.IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address); return(addr.ToString()); }
private void button1_Click(object sender, EventArgs e) { //System.IO.File.WriteAllText(@"\\Mac\Home\Downloads\晴空暑假\PCObserverStudent\server_PHP\1.txt", string.Empty); Config config = new Config(); int mode = config.check(); //blacklist:0 whitelist:1 Console.WriteLine(mode); Stopwatch watch = Stopwatch.StartNew(); ArrayList process = new ArrayList(); foreach (Process ps in Process.GetProcesses()) { if (!process.Contains(ps.ProcessName)) { process.Add(ps.ProcessName); } } string ans = ""; if (mode == 0) { textBox1.Text = "黑名单模式"; BlackList checker = new BlackList(); ans = checker.Check(process); } else { textBox1.Text = "白名单模式"; foreach (Process ps in Process.GetProcesses()) { WhiteList checker = new WhiteList(); ans = checker.check(process); } } string hostname = System.Net.Dns.GetHostName(); IPAddress ddr = new System.Net.IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address); string ip = ddr.ToString(); string postData = string.Format("s={0}&guid={1}&hostname={2}&ip={3}&mode={4}", ans, guid, hostname, ip, mode); UTF8Encoding encoding = new UTF8Encoding(); byte[] bytepostData = encoding.GetBytes(postData); string URL = "http://localhost:8000/logrecv.php"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); ((HttpWebRequest)request).UserAgent = ".NET Framework Example Client"; request.Method = "POST"; request.ContentLength = bytepostData.Length; request.ContentType = "application/x-www-form-urlencoded"; Stream dataStream = request.GetRequestStream(); dataStream.Write(bytepostData, 0, bytepostData.Length); dataStream.Close(); WebResponse response = request.GetResponse(); richTextBox1.Text = ans; }
private void Form1_Load(object sender, EventArgs e) { Config config = new Config(); int mode = config.check(); //blacklist:0 whitelist:1 Console.WriteLine(mode); Stopwatch watch = Stopwatch.StartNew(); ArrayList process = new ArrayList(); foreach (Process ps in Process.GetProcesses()) { if (!process.Contains(ps.ProcessName)) { process.Add(ps.ProcessName); } } string ans = ""; if (mode == 0) { BlackList checker = new BlackList(); ans = checker.Check(process); } else { foreach (Process ps in Process.GetProcesses()) { WhiteList checker = new WhiteList(); ans = checker.check(process); } } Guid Guid = Guid.NewGuid(); string guid = Guid.ToString(); string hostname = System.Net.Dns.GetHostName(); IPAddress ddr = new System.Net.IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address); string ip = ddr.ToString(); string postData = string.Format("s={0}&guid={1}&hostname={2}&ip={3}&mode={4}", ans, guid, hostname, ip, mode); UTF8Encoding encoding = new UTF8Encoding(); byte[] bytepostData = encoding.GetBytes(postData); string URL = "http://192.168.1.131:2333/test.php"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); ((HttpWebRequest)request).UserAgent = ".NET Framework Example Client"; request.Method = "POST"; request.ContentLength = bytepostData.Length; request.ContentType = "application/x-www-form-urlencoded"; Stream dataStream = request.GetRequestStream(); dataStream.Write(bytepostData, 0, bytepostData.Length); dataStream.Close(); WebResponse response = request.GetResponse(); //Console.WriteLine(((HttpWebResponse)response).StatusDescription); //Stream data = response.GetResponseStream(); //response.Close(); }
public bool valida_link() { recupera_session(); System.Net.IPAddress oAddr; bool respuesta; string perfilStr, url, sessionStr, usuario, mIP, mEquipo, winSession, descripcion; Int32 perfilInt; DateTime fecha = DateTime.Now; sessionStr = lb_session_user.Text; sessionStr = sessionStr.Replace(":", ""); sessionStr = sessionStr.Replace("/", ""); usuario = lb_id_usuario.Text; perfilStr = id_perfil; perfilInt = Convert.ToInt32(perfilStr); url = Request.RawUrl; url = PRO.ObtenerLink(url); lb_session_user.Visible = false; lb_session_empresa.Visible = false; respuesta = PRO.obtiene_perfil(perfilInt, url); if (respuesta == false) { try { oAddr = new System.Net.IPAddress(System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList[0].Address); mIP = oAddr.ToString(); } catch (Exception ex) { mIP = "0.0.0.0 " + ex.Message.ToString(); } try { mEquipo = System.Net.Dns.GetHostName(); } catch (Exception ex) { mEquipo = "EQUIPO DESCONOCIDO " + ex.Message.ToString(); } try { winSession = System.Security.Principal.WindowsIdentity.GetCurrent().Name; } catch (Exception ex) { winSession = "SESION DESCONOCIDA " + ex.Message.ToString(); } descripcion = "INTENTO INGRESAR A MODULO NO AUTORIZADO CYR_ESSBIO"; PRO.Insertamos_log(sessionStr, perfilStr, usuario, url, fecha.ToString(), mEquipo, winSession, mIP, descripcion); string ser = Server.MapPath(@".\CorreoAlerta.htm"); PRO.EnviarAlerta(ser, sessionStr, perfilStr, usuario, url, fecha.ToString(), mEquipo, winSession, mIP, descripcion); Session.Abandon(); Response.Redirect("administracion.aspx"); } return(respuesta); }
// Use this for initialization void Start() { m_state = State.SelectHost; IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); System.Net.IPAddress hostAddress = hostEntry.AddressList[0]; Debug.Log(hostEntry.HostName); m_address = hostAddress.ToString(); }
private void Form1_Load(object sender, EventArgs e) { this.Text = "小蚁智能合约远程服务器 v" + hhgate.AntGateway.ver; //log 本地IP { System.Net.IPAddress[] addressList = Dns.GetHostAddresses(Dns.GetHostName()); System.Net.IPAddress ipv4 = System.Net.IPAddress.Any; System.Net.IPAddress ipv4self = System.Net.IPAddress.Any; foreach (var ip in addressList) { if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && ip.IsIPv6LinkLocal == false) { ipv4self = ip; } } Log("本地ip:" + ipv4self.ToString()); } //启动服务器 { hhgate.CustomServer.BeginServer(); Log("服务器已经启动:http://*:8080/_api/ver"); } {//测试编译器 Log("dotnet 编译器版本:" + gencode.getCompilerStr()); List <string> codes = new List <string>(); codes.Add(System.IO.File.ReadAllText("tcode.cs")); var r = gencode.GenCode(codes, true); Log(r.Errors.Count == 0 ? "dotnet 编译器 正常" : "dotnet 编译器 异常"); Log("测试小蚁编译器"); if (r.Errors.Count == 0) { try { var st = System.IO.File.OpenRead(r.PathToAssembly); using (st) { var bs = Convert(st, this); if (bs != null) { Log("测试小蚁编译器正常"); } } } catch (Exception err) { Log(err.ToString()); Log("测试小蚁编译器失败"); } } } }
/** * * 网关登录 * 网关启动后即登录服务器,更新其在服务器中的信息 * 如果不存在则注册 * * * */ private void UserLogin(string msg, System.Net.IPAddress Ip, int Port) { DataOp dataOp = new DataOp(this.oracleip, this.oracleport, this.database, this.userid, this.password); string ip = Ip.ToString(); //根据ip地址查询记录 OleDbDataReader data = dataOp.GetRowByIndex("GATEWAY_T", "ADDRESS", Ip.ToString()); //如果存在则更新 if (data.HasRows) { string newvalue = "set address = '" + Ip.ToString() + "' , port = " + Port; int rownum = dataOp.UpdateOneRow("GATEWAY_T", newvalue, "ADDRESS", Ip.ToString()); if (rownum != 1) { Console.WriteLine("UpdateOneRow gateway_t error"); } //更新列表网关与电表状态 //Load_InfoList(); } else { //如果不存在则插入 //获取最大索引, int nextid = dataOp.GetMaxId("GATEWAY_T", "Gateway_id") + 1; //插入数据 string value = nextid + ",'default', '" + Ip.ToString() + "'," + Port + ", 'default' , 'active'"; int rownum = dataOp.InsertOneRow("GATEWAY_T", value); //追加记录 //Load_InfoList(); } dataOp.Close(); }
/// Add Devices to the list which we can connect to. public static void OnDevicesDiscovered(System.Net.IPAddress ip, string deviceName) { if (!broadcastingDevices.ContainsKey(deviceName)) { broadcastingDevices.Add(deviceName, ip.ToString()); } if (myState == MyState.refreshing) { myState = MyState.WaitingForConnection; } }
private void device_OnPacketArrival(object sender, CaptureEventArgs e) { var time = e.Packet.Timeval.Date; var len = e.Packet.Data.Length; var packet = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data); var tcpPacket = (PacketDotNet.TcpPacket)packet.Extract(typeof(PacketDotNet.TcpPacket)); if (tcpPacket != null) { var ipPacket = (PacketDotNet.IpPacket)tcpPacket.ParentPacket; System.Net.IPAddress srcIp = ipPacket.SourceAddress; System.Net.IPAddress dstIp = ipPacket.DestinationAddress; int srcPort = tcpPacket.SourcePort; int dstPort = tcpPacket.DestinationPort; var model = new PackageModel() { Time = time.ToLocalTime(), FromIP = srcIp.ToString(), FromPort = srcPort.ToString(), ToIP = dstIp.ToString(), ToPort = dstPort.ToString(), Data = tcpPacket.PayloadData }; if (model.FromIP == this.localIP) { model.ProcName = UtilMethods.ShowPort(model.FromPort); } else { model.ProcName = UtilMethods.ShowPort(model.ToPort); } list.Add(model); //label2.Text = list.Count.ToString(); AddDvgData(this.dgvIP, model, new List <string>() { model.FromIP, model.ToIP }, lockIPObj); if (this.selectFromIP == model.FromIP && this.selectToIP == model.ToIP) { AddDvgData(this.dgvPort, model, new List <string>() { model.FromPort, model.ToPort, model.ProcName }, lockPortObj); } if (this.selectFromPort == model.FromPort && this.selectToPort == model.ToPort) { AddContentPackage(model); } } }