Show Ping Status in list in MVC5 - asp.net

I am Using Asp.net mvc5, I have table with fields like "id", and "server_IP" populated with n-numbers of server ip. And wants to display the status of each IP " success" or "timeout" depending upon ping.
I have used following;
Ping myPing = new Ping();
PingReply reply = myPing.Send("8.8.8.8", 1000);
if (reply != null)
{
ViewData["ip_stat"] = reply.Status;
}
I could not use this in my viewlist so that status of each servers can be shown as
Server Status
8.8.8.8 Success
192.168.10.10 timeout
192.168.100.1 sucess
REGARDS
ARUN SAHANI

Not sure if I have understood your question correctly, but going by the kind of output you are looking for and the way your are initializing the viewstate, I think you should concatenate the ip and the status while passing it into viewstate.
Something like this:
ViewData["ip_stat"] = reply.Address + " " + reply.Status;
Hope it helps.
Edited for the case where addresses are fetched from some table and needed to be passed to viewstate
// suppose this variable has the list of IP addresses from the table
var addresses = new List<string> {"8.8.8.8", "192.168.10.10", "192.168.10.8"}
var ipStatusDict = new Dictionary<string, string>();
//iterate over the list, fetch the status for each ip and add it within the dictionary
foreach(var ip in addresses)
{
var reply = new Ping().Send(ip, 1000);
if (reply != null)
{
ipStatusDict.Add(reply.Address, reply.Status);
}
}
ViewData["ip_stat"] = ipStatusDict;

Related

Get Client Ip Kentico 9

I need to get the country of the customer who comes to the site.
I can use GeoIPHelper.GetCountryByIp("ip")to get Counry, but how can I get the ip address of the client that comes to the site?
Are you using Kentico EMS? If so then to get country of current contact:
var countryId = ContactManagementContext.CurrentContact.ContactCountryId;
var country = CoutryInfoProvider.GetCountryInfo(countryId);
Or
var currentLocation = GeoIPHelper.GetCurrentGeoLocation();
Which also contains country/state based on current request.
{%Ip%} in macro or var clientIp = CMS.Helpers.RequestContext.UserHostAddress
Or do you want to find out ip of existing customers?
That would be a sql query like
select Convert(xml,UserLastLogonInfo)
from COM_Customer Join CMS_User on CustomerUserID = UserID
it will give your xml like:
<info>
<agent></agent>
<ip></ip>
</info>
Looking at your code sample, I think you're in the code behind somewhere. This is possibly more of a general thing with ASP.NET. if that is the case, you can use HttpContext.Current.Request.UserHostAddress to get the IP of the current user.
There can be issues with this however if you're behind something like a load balancer. To combat that, you can try something like the following:
string userAddress = string.Empty;
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
userAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
userAddress = HttpContext.Current.Request.UserHostAddress;
}
var country = GeoIPHelper.GetCountryByIp(userAddress);
CMS.Helpers.RequestContext also works (as Shof says) but again, make sure to cater for any load balancer issues. To be honest, I've always fallen back to just using the HttpContext method from pre-Kentico habit.
GeoLocation currentGeoLocation = GeoIPHelper.GetCurrentGeoLocation();
if (currentGeoLocation != null)
{
var countryAndState = ValidationHelper.GetString(currentGeoLocation.CountryName, "");
var ipCountryCode = ValidationHelper.GetString(currentGeoLocation.CountryCode, "");
var ipRegion = ValidationHelper.GetString(currentGeoLocation.RegionName, "");
var ipCity = ValidationHelper.GetString(currentGeoLocation.City, "");
}
or macro
{% AnalyticsContext.CurrentGeoLocation.Country.CountryName%}
{% AnalyticsContext.CurrentGeoLocation.State%}
{% AnalyticsContext.CurrentGeoLocation.City%}
{% AnalyticsContext.CurrentGeoLocation.Postalcode%}

Smack Roster Entries are null

I am creating a java fx application for openfire chat client.
i am using smack 4.1 rc1 to connect to the server.
i am able to to connect to server send presence information to others and send messages to other users as well.
however i am not able to iterate through the roster.
when i get roster object and debug it its shows a hash map of 3 roster entries that means the roster is getting loaded in roster object. however when i use roster.getentries method to store it into the Collection of roster entries it shows 0 object. even the roster.getentriescount() method returns 0 though i can see the roster user names in the debug view
try {
config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword(mUserName+ "#" + Domain, mPassword)
.setServiceName(HostName)
.setHost(HostName)
.setPort(PortName)
.setResource(Resource)
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.build();
mXmppConnection = new XMPPTCPConnection(config);
mXmppConnection.connect();
mXmppConnection.login();
// Presence presence=new Presence();
Presence presence ;
if(mPresence) presence = new Presence(Presence.Type.available);
else presence = new Presence(Presence.Type.unavailable);
presence.setStatus("On Smack");
XMPPConnection conn=(XMPPConnection) mXmppConnection;
Chat chat = ChatManager.getInstanceFor(mXmppConnection).createChat
("monika#ipaddress");
chat.sendMessage("Howdy from smack!");
// Send the packet (assume we have a XMPPConnection instance called "con").
mXmppConnection.sendPacket(presence);
System.out.println("Connected successfully");
Roster roster = Roster.getInstanceFor(conn);
Collection<RosterEntry> entries = roster.getEntries();
int i=0;
for (RosterEntry entry : entries) {
System.out.println(entry);
i++;
}
System.out.println("Rosters Count - "+ i+ roster.getEntryCount());
has any one encountered the same problem before?
You may have to check if roster is loaded before calling getEntries.
Roster roster = Roster.getInstanceFor(connection);
if (!roster.isLoaded())
roster.reloadAndWait();
Collection <RosterEntry> entries = roster.getEntries();
thanks for Deepak Azad
Here full code
public void getRoaster(final Callback<Collection<RosterEntry>> callback) {
final Roster roster = Roster.getInstanceFor(connection);
if (!roster.isLoaded())
try {
roster.reloadAndWait();
} catch (SmackException.NotLoggedInException | SmackException.NotConnectedException | InterruptedException e) {
e.printStackTrace();
}
Collection<RosterEntry> entries = roster.getEntries();
for (RosterEntry entry : entries) {
android.util.Log.d(AppConstant.PUBLIC_TAG, entry.getName());
}
}
I have just solved this problem. I'm using OpenFire as XMPP server. I checked the field "Subscription" in the users in roster and it was "None". After change it by "Both", it worked, and entries are being fetched.
Hope it helps!

how to get User IP address in asp.net?

This is the label
<asp:Label ID="lblIp" runat="server"></asp:Label>
Here Code I used to get user IP address
string VisitorsIPAddr = string.Empty;
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
lblIp.Text = VisitorsIPAddr;
}
else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
lblIp.Text = VisitorsIPAddr;
}
but Always I got the same result. That was 127.0.0.1 and always it goes to else if state.
further
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] did not give any result. It always give nothing
You are running the application at your own machine therefor you are the one sliding there, so you will always get 127.0.0.1 in the else if.
If you want to see another IP open the app and relevant port and get there with another machine.
Also the HTTP_X_FORWARDED_FOR is not always there (usually from normal web requests it will be but there are exceptions).
I think thats what Kundan Singh Chouhan tried to suggest, hope I am not wrong.

using ASP.NET to display the visitor location like country, state and city in master page

How to get visitor location like country, state and city using ASP.NET, i saw some examples All are based on IP Address to get the Details(based on some free services), now my problem is above example that services only working registered Ip addresses, but now my task is when user browse the my asp.net website, display the Country, state and city how it possible, please give me any suggestion, urgent
Thank u
hemanth
You can use a WebClient request to something like ipinfodb, if you register (free) for an api key:
var client = new System.Net.WebClient();
var ip = Request.UserHostAddress;
var url = string.Format("http://api.ipinfodb.com/v3/ip-city/?key={0}&ip={1}", apiKey, ip);
var info = client.DownloadString(url).ToString();
Then parse and display the info in your page.
There are many IP locator APIs, whichever one you use, the general idea is the same, but you will parse the info result differently depending on the service.
But walther is correct, getting location info from IP addresses isn't always reliable.
here my solution in asp.net c#
public async void MakeUserLoginHistoryAsync()
{
#region Get data from ip2location
var ip = "43.240.503.78";
string apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var httpClient = new HttpClient();
var url = string.Format("https://api.ip2location.io/?key={0}&ip={1}", apiKey, ip);
var response = await httpClient.GetStringAsync(url);
Console.WriteLine($"{response}");
#endregion
}
here ip will be your public ip
*apiKey you need to get from their official website https://www.ip2location.io/

How can i get IP address in worklight?

I am unable to get ip address of client using this following code. How can i modify this code? Please help me
This is .js code
function getIP(){
//return WL.Server.configuration["local.IPAddress"];
//alert(publicWorklightHostname);
var request = WL.Server.getClientRequest();alert('IP');
var ip = request.getHeader('x-client-ip');
alert(ip);
}
Try to use this
var request = WL.Server.getClientRequest();
var IPAddress = request.getHeader('x-forwarded-for');
Edit:
Also you can try this
WL.Device.getNetworkInfo(function (networkInfo) {
alert (networkInfo.ipAddress);
});

Resources